问题描述
我编写了一个用于在数据库中搜索关键字的简单查询。
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();
现在Codeigniter生成的查询是这样的:
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!
推荐答案
如果深入研究CodeIgniter的内部结构,您会注意到 $ this-> db-> like()
函数转义包含的特殊字符-当然包括%
。
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, %
.
我认为 like()
不会对您的特殊需求有所帮助。我猜,最好的选择是绕过此问题,并使用包含您的 Like
子句的 where
函数:
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();
这篇关于Codeigniter:$ this-> db-> like()的怪异行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!