[英]Having trouble with PDO Prepared Statement and “LIKE”
因此,首先,我知道在使用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/zh/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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.