所以,首先,我知道在使用PDO准备LIKE
语句时必须遵循某些规则。我已经查找了这些内容,并且正在尽力遵循它们,但是即使我知道查询本身是合法的,查询始终不返回任何结果(MySQL命令行客户端可以正确处理查询)。
这是针对学校项目;我需要为一家虚构的书店制作一个带有MySQL/php后端的网站。
我在一个名为 DBConnection
的 php 脚本中有一个类。它位于单独的命名空间中(因此PDO对象和函数的反斜杠)。这是其中的一部分:
<?php
class DBConnection {
// ...
public function prepAndExecute($sql, $args) {
try {
$stmt = $this->conn->prepare($sql);
for($i = 1; $i <= count($args); $i++) {
$stmt->bindValue($i, $args[$i-1], PDO::PARAM_STR);
}
$stmt->execute();
return $stmt;
} catch(PDOException $e) {
return false;
}
}
}
?>
我尝试运行的实际 MySQL 查询:
SELECT ISBN, Title, Author, Price FROM Book WHERE Title LIKE "%rich%";
我尝试使用 PDO 准备的声明在网站上运行它:
<?php
// based on the search form from the previous page
// (all values are set correctly by the form, already tested)
$criteria = $_POST["searchCriteria"]; // "Title" (from a <select> element)
$term = $_POST["searchTerm"]; // "rich" (from the text box)
$conn = new DBConnection(); // uses namespace correctly, just didn't
// include here for simplicity
$sql = "SELECT ISBN, Title, Author, Price FROM Book WHERE ? LIKE ?";
$stmt = $conn->prepAndExecute($sql, array($criteria, "%" . $term . "%"));
// I have also tried $term = "%" . $term . "%", still no luck
echo $stmt->rowCount(); // 0
?>
我在 MySQL 命令行中运行了上述查询,并按预期得到了 1 个结果。我知道类/函数有效,因为我使用相同的函数来运行所有其他 SELECT 和 INSERT 查询,并且在我尝试运行此 LIKE 语句之前没有任何问题。
我做错了什么吗?因为我仔细检查了所有内容,并且可以发誓我做对了。
http://php.net/manual/en/pdostatement.bindparam.php
$sth = $dbh->prepare('SELECT * FROM `users` WHERE `firstname` LIKE :keyword');
// Put the percentage sing on the keyword
$keyword = "%".$keyword."%";
// Bind the parameter
$sth->bindParam(':keyword', $keyword, PDO::PARAM_STR);