I want to combine AND OR mysql queries in CI. I have already seen this thread: http://codeigniter.com/forums/viewthread/92818/. But they don\'t provide the exact solution th
I needed this for CodeIgniter 2, but I needed the values still escaped so csotelo's answer wasn't good for me and I didn't want to rewrite the whole query like Shawn C's answer, so I ended up doing this:
$this->db->where('LastName', $lastName);
$this->db->where('Age', $age, false);
$this->db->where('1 AND ( 0', null, false); // This one starts the group
$this->db->or_where('FirstName', $firstName1);
$this->db->or_where('FirstName', $firstName2);
$this->db->or_where('Gender', $gender);
$this->db->or_where('Country', $country);
$this->db->or_where('0 )', null, false); // This one ends the group
$query = $this->db->get('Persons');
Which generates the following query:
SELECT *
FROM (`Persons`)
WHERE `LastName` = 'Svendson'
AND Age = 12
AND 1 AND ( 0 -- This one starts the group
OR `FirstName` = 'Tove'
OR `FirstName` = 'Ola'
OR `Gender` = 'M'
OR `Country` = 'India'
OR 0 ) -- This one ends the group
Which would be the same as this:
SELECT * FROM (`Persons`) WHERE
`LastName` = 'Svendson' AND Age = 12 AND 1 AND
(0 OR `FirstName` = 'Tove' OR `FirstName` = 'Ola' OR `Gender` = 'M' OR `Country` = 'India' OR 0)