在PDO中实现LIKE查询 [英] implement LIKE query in PDO
问题描述
我在PDO中实施LIKE时遇到问题
I am running problems in implementing LIKE in PDO
我有这个查询:
$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'";
$params = array($var1, $var2);
$stmt = $handle->prepare($query);
$stmt->execute($params);
我检查了$var1
和$var2
它们包含我要搜索的两个词,我的PDO正常工作,因为我的某些查询SELECT
INSERT
它们都可以工作,只是我不熟悉LIKE
在PDO中.
I checked the $var1
and $var2
they contain both the words I want to search, my PDO is working fine since some of my queries SELECT
INSERT
they work, it's just that I am not familiar in LIKE
here in PDO.
结果不返回.我的$query
在语法上是否正确?
The result is none returned. Do my $query
is syntactically correct?
推荐答案
您必须在$params
中而不是查询中包括%
符号:
You have to include the %
signs in the $params
, not in the query:
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
如果您在之前的代码中查看生成的查询,则会看到类似SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%'
的内容,因为prepared语句在一个已加引号的字符串内引用了您的值.
If you'd look at the generated query in your previous code, you'd see something like SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%'
, because the prepared statement is quoting your values inside of an already quoted string.
这篇关于在PDO中实现LIKE查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!