Adil Sarwar Adil Sarwar - 7 months ago 10
PHP Question

Using AND between two corresponding elements of Array and OR between them in Codeigniter Active Record

Pardon me if I'm being dumb, been coding for 30 hours straight

Final Output Required:


SELECT * FROM
cities_extended
WHERE (
state_code
= 'MO' AND
county
= 'GREENE') OR (
state_code
= 'NY' AND
county
= 'GREENE')


My Try:
I have this query (written for testing), I wrote the code for it in codeigniter but I've failed to properly convert it into codeigniter's Active Record. I'm aware of where_in and or_where_in functions of codeigniter. I tried the following code:

// some code
$counties = $query->result_array();
for($i = 0; $i < count($counties); $i++)
{
$this->db->or_where('county', $counties[$i]['county']);
$this->db->where('state_code', $counties[$i]['state_code']);
}
$this->db->select('zip');
$zips_query = $this->db->get('cities_extended');
return $this->db->last_query();
// some code


This gives the following output:

"SELECT `zip` FROM `cities_extended` WHERE `county` = 'Laclede' AND `state_code` = 'MO' OR `county` = 'Greene' AND `state_code` = 'MO' OR `county` = 'Webster' AND `state_code` = 'MO'"


Crux: HOW DO I PUT ( county ='HELP' AND state_code = 'ME' ) OR ( county= 'WILL' AND state_code ='YOU') using Codeigniter's Active Record.

Answer

You can do like in the below code

$this -> db -> select('*') -> from ('cities_extended') -> where("(state_code = 'MO' AND county= 'GREENE')") -> or_where("(state_code = 'NY' AND county = 'GREENE')");

$result = $this -> db -> get();

Edit: Please do the below one

for($i = 0; $i < count($counties); $i++)
{
   $this->db->or_where("'county' = '".$counties[$i]['county']."' AND 'state_code' = '".$counties[$i]['state_code."']");
}