Home > OS >  Codeigniter query where_in array
Codeigniter query where_in array

Time:03-15

I have website with various filters including CATEGORY filter. User can choose multiple categories as well as one. In MYSQL database, field for the 'po_category' is an array (64, 93, 97). So, in codeigniter I have the following code:

$kategorija = $this->input->post('kategorija');

$this->db->select('*'); 
$this->db->from('jobs');

    if(!empty($kategorija)) {
        $cat_array = explode(',', $kategorija);
        $count_items = count($cat_array);
        
        
        
        if($count_items == '1') {
            $this->db->where("find_in_set($kategorija, po_category)");
        } else {
            $this->db->group_start();
            $count = 0;
            foreach($cat_array as $item) {
                $count  ;
                
                if($count == '1') {
                    $this->db->where_in("find_in_set($item, po_category)");
            
                } else {
                    $this->db->or_where("find_in_set($item, po_category)");
                }
            }
            $this->db->group_end();
        }
    }

It works fine only if in filter I choose first number in category array (64). I guess I have to use 'where_in' but it doesn't work as it should.

Any suggestion?

CodePudding user response:

The where_in syntax for CodeIgniter is like this:

where_in('column', $array);

Why do you use find_in_set?

CodePudding user response:

You can replace following code:

foreach($cat_array as $item) {
  $count  ;
            
  if($count == '1') {
      $this->db->where_in("find_in_set($item, po_category)");  
   } else {
      $this->db->or_where("find_in_set($item, po_category)");
   }
}

With where_in:

$this->db->where_in('po_category', $cat_array);
  • Related