[英]PHP PDO MySQL LIKE and prepared statements
Assume $search
is a string from user input, and $db
is a valid PDO reference. 假设
$search
是来自用户输入的字符串,而$db
是有效的PDO引用。
From what I understand, the following block is preferred and should work: 据我了解,以下块是首选,应该可以工作:
$imageStatement = $db->prepare("SELECT
images.whatever
FROM images
WHERE images.title LIKE :titleSearch OR images.description LIKE :descriptionSearch");
$imageStatement->bindValue(':titleSearch', "%{$search}%");
$imageStatement->bindValue(':descriptionSearch', "%{$search}%");
$images = $imageStatement->fetchAll();
It gives back 0 results, while the following gives back the expected returns: 它返回0个结果,而下面的结果则返回预期的回报:
$search = $db->quote("%{$search}%");
$images = $db->query("SELECT
images.whatever
FROM images
WHERE images.title LIKE {$search} OR images.description LIKE {$search}")->fetchAll();
What am I doing wrong? 我究竟做错了什么?
You never executed your PDO statement. 您从未执行过PDO语句。 After binding your parameters, call
execute
before retrieving your results. 绑定参数后,在获取结果之前调用
execute
。
$imageStatement->bindValue(':titleSearch', "%{$search}%");
$imageStatement->bindValue(':descriptionSearch', "%{$search}%");
$imageStatement->execute(); //ADD THIS STATEMENT
$images = $imageStatement->fetchAll();
PDO's query
function does not require you to call execute
, because it is not a parameterized query. PDO的
query
功能不需要您调用execute
,因为它不是参数化查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.