2
votes

I am using codeigniter framework and i want to create a OR WHERE statement using foreach loop,

Below is my code,

$wh_q = array('ec_date >' => $start, 'ec_date <=' => $end);

This will produce query as WHERE ec_details.date > '2016-11-01 00:00:00' AND ec_details.date <= '2017-01-07 00:00:00'

Now i want to append few more criteria in abover query string with AND ec_details.user_id = '5' OR ec_details.user_id = '6' and so on.

Now user_id, 5 and 6 are coming from array results,

$user_string = '5,6';
$users_array = explode(",",$user_string);

foreach ($users_array as $user) {
   $query = array('ec_details.user_id' => $user);
}

Then i am merging above $query array in original $wh_q array

$wh_q = array_merge($wh_q, $query);

And finally i select where as below,

$this->db->where($wh_q);

But this will not produce my required query, but will just create like below,

`WHERE `ec_details`.`date` > '2016-11-01 00:00:00' AND `ec_details`.`date` <= '2017-01-07 00:00:00'`AND `ec_details`.`user_id` = '6'`

How can i add AND OR WHERE statements using foreach loop in codeigniter?

Thank you,

3
I assume you want to get details from ec_detail table for user_id 5 and 6 between start and end range, is that it? - Malik Mudassar
@MalikMudassar, yes correct - rjcode
see edited answer...if works accept it thanks... - Hikmat Sijapati

3 Answers

1
votes

Try as below...

$wh_q = array('ec_date >' => $start, 'ec_date <=' => $end);//condition first

$user_string = '5,6';
$users_array = explode(",",$user_string);

foreach ($users_array as $user) {
   $query []= array('ec_details.user_id' => $user);//second condition
}

//print_r($query) //multidimensional array

Query

$this->db->where($wh_q);

$total = count($query);
for($i=0;$i<$total;$i++){
    $this->db->or_where($query[$i]);
    }
1
votes

You can try like this, create a complete where string like this

$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);

And check, this will work.

EDIT

OR you can give or condition like this

$this->db->where('name !=', $name);
$this->db->or_where('id >', $id);  // Produces: WHERE name != 'Joe' OR id > 50
0
votes

If you you need to check only user id then better you can also user IN like below.

$user_string = '5,6'; $users_array = explode(",",$user_string); 
$this->db->where_in('id', $users_array);

and If you want to use only OR and And statement

then use below code

$this->db->where('ec_date >',$start,false);
$this->db->where('ec_date <=', $end,false);
$user_string = '5,6';
$users_array = explode(",",$user_string);
$userqry = array();
foreach ($users_array as $user) {
   $userqry[] = "ec_details.user_id ='".$user."'";
}
$userqrystr = implode(" OR ",  $userqry);
$this->db->where($userqrystr,false,false);

This query look like

WHERE `ec_details`.`date` > '2016-11-01 00:00:00' AND `ec_details`.`date` <= '2017-01-07 00:00:00' AND (`ec_details`.`user_id` = '6' OR `ec_details`.`user_id` = '5')