Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"SELECT ... IN (SELECT ...)" query in CodeIgniter

Tags:

codeigniter

I have a query similar to this:

SELECT username 
FROM users 
WHERE locationid IN 
  (SELECT locationid FROM locations WHERE countryid='$')

$ is a value I get from end user.

How could I run this query in CodeIgniter? I can't find a solution in CodeIgnite's user guide.

Thank you so much for your answers!

Regards!

like image 601
Hung Tran Avatar asked Jun 11 '11 11:06

Hung Tran


3 Answers

Look here.

Basically you have to do bind params:

$sql = "SELECT username FROM users WHERE locationid IN (SELECT locationid FROM locations WHERE countryid=?)"; 

$this->db->query($sql, '__COUNTRY_NAME__');

But, like Mr.E said, use joins:

$sql = "select username from users inner join locations on users.locationid = locations.locationid where countryid = ?"; 

$this->db->query($sql, '__COUNTRY_NAME__');
like image 64
CristiC Avatar answered Nov 16 '22 08:11

CristiC


Note that these solutions use the Code Igniter Active Records Class

This method uses sub queries like you wish but you should sanitize $countryId yourself!

$this->db->select('username')
         ->from('user')
         ->where('`locationId` in', '(select `locationId` from `locations` where `countryId` = '.$countryId.')', false)
         ->get();

Or this method would do it using joins and will sanitize the data for you (recommended)!

$this->db->select('username')
         ->from('users')
         ->join('locations', 'users.locationid = locations.locationid', 'inner')
         ->where('countryid', $countryId)
         ->get();
like image 6
Hailwood Avatar answered Nov 16 '22 08:11

Hailwood


Also, to note - the Active Record Class also has a $this->db->where_in() method.

like image 5
tison Avatar answered Nov 16 '22 09:11

tison