Search code examples
phpcodeigniterwhere-clausecodeigniter-3query-builder

Pass an array of diverse WHERE conditions as an array from the Controller to the Model in a CodeIgniter application


I'm using CodeIgniter 3 to build a website. Now I have an issue with getting data from the database.

This is my Model:

public function Get($arr_condition = null)
{
     if (!is_null($arr_condition))
     {
        $this->db->where($arr_condition);
     }
     $query = $this->db->get('cus');
     if ($query->num_rows() > 0)
     {
        return $query->result_array();
     }
     return false;
}

In my Controller, I use an array ($arr_condition) to list all conditional expressions.

$arr_condition['Cus_team'] =  1;
$arr_condition['Cus_user != '] =  2;
$arr_condition['Cus_phone LIKE'] = 09900000;
$arr_condition['Cus_role >'] = 1;

$result = $this->M_cus_dal->get($arr_condition);

My code is working perfectly until I need a condition with where_in(), I tried:

$arr_condtion['Cus_id IN']= array('1,2,3');

But, It not work.

Please give me an ideal to resolve this issue.


Solution

  • You can do something like this:

    In controller pass your where_in condition with another parameter like this

    $where_in = array('1,2,3');
    $result = $this->M_cus_dal->Get($arr_condition,$where_in);
    

    In model method get $where_in as second parameter as add it to where_in clause like this :

    public function Get($arr_condition = null,$where_in = NULL)
    {
         if(!is_null($arr_condition))
         {
            $this->db->where($arr_condition);
         }
         if(! empty($where_in))
         {
           $this->db->where_in('Cus_id',$where_in);
         }
         $query = $this->db->get('cus');
         if($query->num_rows()>0)
         {
            return $query->result_array();
         }
         return false;
    }