phpcodeigniteractiverecordsql-likelogical-grouping

Codeigniter db query clause where not working


I built a query:

 public function getContacts($limit, $start, $search)
{

    $this->db->limit($limit, $start);

    if (!empty($search)) {
        $this->db->like('name', $search);
        $this->db->or_like('last_name', $search);
        $this->db->or_like('phone_number', $search);
        $this->db->or_like('created_at', $search);
        $this->db->or_like('note', $search);
    }



    $query = $this->db->get_where('contact', array('user_id' => 3));

    return $query->result_array();

}

but the where clause does not work. It should return only results with user_id equals to 3 but it returns everything.

What is wrong?

This is the query executed:

SELECT * FROM `contact` WHERE name LIKE '%stefano%' ESCAPE '!' OR last_name LIKE '%stefano%' ESCAPE '!' OR phone_number LIKE '%stefano%' ESCAPE '!' OR created_at LIKE '%stefano%' ESCAPE '!' OR note LIKE '%stefano%' ESCAPE '!' AND `user_id` = 3 LIMIT 2

Tried this query in Workbench and still ignoring the AND user_id = 3. If my logic is not wrong it should return only rows where user_id = 3 but returns all.


Solution

  • you need to add group_start() and group_end().like this.

     if (!empty($search)) {
          $this->db->group_start();
            $this->db->like('name', $search);
            $this->db->or_like('last_name', $search);
            $this->db->or_like('phone_number', $search);
            $this->db->or_like('created_at', $search);
            $this->db->or_like('note', $search);
            ->group_end();
        }