Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter: Weird behaviour of $this->db->like()

Tags:

codeigniter

I've written a simple query for searching a keyword in the database.

$keyword = "keyword sample"; 
$keyword = str_replace(" ", "%", $keyword);   

$this->db->select('*')->from('table')
           ->like('column', "%".$keyword."%")->get();

Now the query generated by Codeigniter is like this:

SELECT * FROM (`table`) WHERE `column` LIKE '%keyword\%sample%'

Where is the trailing \ coming from in the query? This is making an erroneous search and not returning the data that is actually in the db. I've checked everything and nothing seems to be wrong with the code I've written. Please help!

like image 675
CobaltBabyBear Avatar asked Mar 20 '14 20:03

CobaltBabyBear


1 Answers

You just try it like this:

$this->db->select('*')
$this->db->from('table');
$this->db->like('column', $keyword);
return $this->db->get()->result_array();

If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are 'before', 'after' and 'both' (which is the default).

example:

$this->db->select('*')
$this->db->from('table');
$this->db->like('column', $keyword, 'before');
return $this->db->get()->result_array();

If you do not want to use the wildcard (%) you can pass to the optional third argument the option 'none'.

example:

$this->db->select('*')
$this->db->from('table');
$this->db->like('column', $keyword, 'none');
return $this->db->get()->result_array();

BUT, for your example you must need to search like "%keyword sample%", or like "%keyword%" OR "%simple%";

For example:

$this->db->like('column', 'keyword simple');
// Produces: WHERE column LIKE '%keyword simple%' 

OR

$this->db->like('column', 'keyword');
$this->db->or_like('column', 'simple');
// Produces: WHERE column LIKE '%keyword%' OR column LIKE '%simple%'  

More, you can read CodeIgniter User Guide

like image 183
Erman Belegu Avatar answered Oct 20 '22 00:10

Erman Belegu