php 在 PDO 中实现 LIKE 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11117134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
implement LIKE query in PDO
提问by Leandro Garcia
I am running problems in implementing LIKE in PDO
我在 PDO 中实现 LIKE 时遇到问题
I have this query:
我有这个查询:
$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'";
$params = array($var1, $var2);
$stmt = $handle->prepare($query);
$stmt->execute($params);
I checked the $var1and $var2they contain both the words I want to search, my PDO is working fine since some of my queries SELECTINSERTthey work, it's just that I am not familiar in LIKEhere in PDO.
我检查了它们$var1,$var2它们包含我想要搜索的两个词,我的 PDO 工作正常,因为我的一些查询SELECTINSERT它们可以工作,只是我对LIKEPDO不熟悉。
The result is none returned. Do my $queryis syntactically correct?
结果没有返回。我$query的语法正确吗?
回答by Carlos Campderrós
You have to include the %signs in the $params, not in the query:
您必须在 中包含%符号,而$params不是在查询中:
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
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.
如果您查看之前代码中生成的查询,您会看到类似 的内容SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%',因为准备好的语句在已引用的字符串中引用您的值。
回答by Madara's Ghost
No, you don't need to quote prepare placeholders. Also, include the % marks inside of your variables.
不,您不需要引用准备占位符。此外,在变量中包含 % 标记。
LIKE ?
And in the variable: %string%
在变量中: %string%
回答by Miqdad Ali
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
回答by Grant
Simply use the following:
只需使用以下内容:
$query = "SELECT * FROM tbl WHERE address LIKE CONCAT('%', :var1, '%')
OR address LIKE CONCAT('%', :var2, '%')";
$ar_val = array(':var1'=>$var1, ':var2'=>$var2);
if($sqlprep->execute($ar_val)) { ... }
回答by Dinesh Goyal
You can see below example
你可以看到下面的例子
$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
Hope it will work.
希望它会起作用。

