Search code examples
phpcodeigniterwhere-clausequery-builderlogical-grouping

CodeIgniter SELECT query with WHERE clause containing equals, IN, and LIKE as well as AND and OR is not returning correct results


This is my function where I have written the select query

function userList($name,$logged_id,$friendlist)
{
       
    $this->db->select("concat((mu.first_name),(' '),(mu.last_name)) AS full_name,mu.user_id,user_type",FALSE);
    $this->db->from("mst_users as mu");        
    $this->db->where("user_status", "1");
    $this->db->where_in("user_id",$friendlist);
    $this->db->where('user_id !=', $logged_id,false);
    
    $this->db->where("email_verified", "1");        
    $this->db->where("mu.first_name LIKE '%$name%'");        
    $this->db->or_where("mu.last_name LIKE '%$name%'");            
    //$this->db->limit("3");
    $query = $this->db->get();
    return $query->result_array();  
}

This is my function call from the controller

function userList(){
    $arr_friend=array(127, 139, 138);
    $user_list = $this->search_model->userList(a,137,$arr_friend);   
}

This is the out put of the query.This out is wrong.

full_name   user_id     user_type   
Grace          1          2
admina         126        3
hancy          127        1
vaibhavaaa     132        1
arjun          137        1
ashish         138        3
sofia          139        1
emma           140        3
vaibhav        147        3
ashish         148        1

I want the record only for 127, 139, 138 these Id

full_name   user_id     user_type   

hancy          127        1 
ashish         138        3
sofia          139        1

Solution

  • this because you use where_or in wrong way, replace this:

    $this->db->where("mu.first_name LIKE '%$name%'");        
    $this->db->or_where("mu.last_name LIKE '%$name%'");
    

    with:

    $this->db->where("(mu.first_name LIKE '%$name%'", FALSE);        
    $this->db->or_where("mu.last_name LIKE '%$name%')", NULL, FALSE);