Codeigniter: strange behavior $ this-> db-> like ()

I wrote a simple query to search for a keyword in a database.

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

Now the query created by Codeigniter looks like this:

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

Where is the final \ included in the request? This does an erroneous search and does not return data that is actually in db. I checked everything and nothing looks like the code I wrote. Please, help!

+8
codeigniter
source share
3 answers

If you delve a bit into the internal $this->db->like() CodeIgniter, you will notice that $this->db->like() escapes the special characters it contains, including, of course, % .

I don't think like() will help you with your specific needs. I believe the best option would be to get around the problem and use the where function containing the LIKE :

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

You just try this as follows:

 $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 pattern (%) is located, you can use the optional third argument. Your options are "before", "after" and "both" (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 character (%), you can go to the optional third argument with the "none" option.

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 need to search, for example, "%keyword sample%" , or as "%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%' 

For more details, you can read the CodeIgniter User Guide

+18
source share

Use the escape_like_str() method.

The escape_like_str() method should be used when strings are to be used in LIKE conditions, so that LIKE wildcards % , _ in the string are also properly escaped. It cannot automatically add an ESCAPE condition ! for you, and so you have to do it manually.

Hope this helps.

 $keyword = "keyword sample"; $sql = "SELECT id FROM table WHERE column LIKE '%" . $this->db->escape_like_str($keyword)."%' ESCAPE '!'"; 

Source: - https://www.codeigniter.com/userguide3/database/queries.html

0
source share

All Articles