phpcodeigniterwhere-clausesql-likelogical-grouping

How to parenthetically group WHERE clause conditions in CodeIgniter's active record


I found a problem in my codeigniter app. I've written a simple search query using 4 different like and or_like.

$q = $this->db->select('*')
->from('table')
->like('col', $search_string1, both)
->or_like('col', $search_string2, both)
->or_like('col', $search_string3,  both)
->or_like('col', $search_string4, both)
->get()->results

And it works as I wanted, but I decided to add new col in my table called "active" and I want to display only rows that got active = 1. So I tried to add where to my query, but it didn't worked as I expected.

$q = $this->db->select('*')
->from('table')
->where('active', 1)
->like('col', $search_string1, both)
->or_like('col', $search_string2, both)
->or_like('col', $search_string3,  both)
->or_like('col', $search_string4, both)
->get()->results

This query show also rows that got active set as 0. How can I fix that to display only rows with active = 1 in CodeIgniter?


Solution

  • Hello Can you please use following code

    $q = $this->db->select('*')
    ->from('table')
    ->where('active', 1)
    ->where("(col LIKE '%".$search_string1."%' OR col LIKE '%".$search_string2."%' OR col LIKE '%".$search_string3."%' OR col LIKE '%".$search_string4."%')", NULL, FALSE)
    ->get()->results;
    

    Thanks