Home > Software design >  Search multiple categories (FIND_IN_SET)
Search multiple categories (FIND_IN_SET)

Time:11-27

I have project in Codeigniter where user can search thorugh mulitple categories. In my database, category field is comma separated string (46, 53, 76).

When user select category in filters (46) and match with first category in database, it works fine but, if user select another category (53), query doesn't work properly. Similar problem ocure when user select multiple categories.

My code is something like:

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

I wonder if 'find_in_set' works in this structure.

CodePudding user response:

In my database, category field is comma separated string ('46, 53, 76').

When user select category in filters (46) and match with first category in database, it works fine but, if user select another category (53), query doesn't work properly.

There is no 53 in your values list! It contains the value ' 53' (with leading space char) which differs from the value to be searched for. And hence your searching gives negative result.

SELECT FIND_IN_SET(  53 , '46, 53, 76'),
       FIND_IN_SET( '53', '46, 53, 76'),
       FIND_IN_SET(' 53', '46, 53, 76');    

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=81f440fd21b450924f21e769039ad1db

PS. Trailing spaces are taken into account too.

CodePudding user response:

There is space after comma in your po_category field.

So you need to remove it.

You can try like that.

$this->db->where("find_in_set($item, REPLACE(po_category, ' ', ''))");
$this->db->or_where("find_in_set($item, REPLACE(po_category, ' ', ''))");
  • Related