Search code examples
phpcodeigniteractiverecordsql-likequery-builder

CodeIgniter's $this->db->like() method is automatically escaping percent symbols in the input string


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.


Solution

  • If you dig a bit into CodeIgniter's internals, you'll notice that the $this->db->like() function escapes special characters it contains - including, of course, %.

    I don't think like() will help you much with your particular needs. Your best bet, I guess, would be to bypass the problem and use a where function containing your LIKE clause:

    $this->db->select('*')->from('table')->where("column LIKE '%$keyword%'")->get()->result_array();