Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Like clause CodeIgniter

I'm trying to use multiple 'Like' to look for matches in more than one column.

PHP & mysql:

$area = $this->session->userdata('area');
if($area == 'inbox'){

   $this->db->where('receiver',$user); 
   $this->db->where('receiver_deleted !=','yes');

   }elseif($area == 'sent'){
   $this->db->where('sender',$user); 
   $this->db->where('sender_deleted !=','yes');
}

$this->db->like('sender',$k);
$this->db->or_like('msg',$k); 


$this->db->from('messages');
$this->db->join('users','users.username = messages.sender','inner');

$this->db->order_by('read','no');
$sql = $this->db->get();

if($sql->num_rows > 0){

 return $sql->result();
}else{

 echo "failed!";
     }

I've also tried:

$this->db->like('sender',$k); 
$this->db->like('msg',$k); 

the first one nothing happens. The second one only one is executed, in this case the first like. I cannot get both to work at the same time.

Any help will be appreciated, Mike

like image 813
Mike Spider Avatar asked Dec 19 '22 15:12

Mike Spider


2 Answers

for this, you should use Grouping with where clause.

$area = $this->session->userdata('area');
if($area == 'inbox'){

   $this->db->where('receiver',$user); 
   $this->db->where('receiver_deleted !=','yes');

   }elseif($area == 'sent'){
   $this->db->where('sender',$user); 
   $this->db->where('sender_deleted !=','yes');
}
$this->db->group_start();  //group start
$this->db->like('sender',$k);
$this->db->or_like('msg',$k); 
$this->db->group_end();  //group ed
like image 77
ni3solanki Avatar answered Dec 24 '22 02:12

ni3solanki


or_like will produce an OR between the two likes. You can pass an array to like to put multiple with an AND between them.

Have you tried doing:

$this->db->like(array('sender' => $k, 'msg' => $k));
like image 20
Thomas Lomas Avatar answered Dec 24 '22 00:12

Thomas Lomas