使用带有%的LIKE运算符进行关键字搜索和PDO预处理语句

Ran*_*ndy 5 php mysql pdo prepared-statement sql-like

我正在尝试使用PDO预处理语句编写关键字搜索.理想情况下,我想利用LIKE运算符来搜索字段值中的子字符串.这是我的代码:

$statement = $this->db->prepare("select * from whatever where title like ? or author like ?");
$statement->execute(array("%$titleKeyword%","%$authorKeyword%"));
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
Run Code Online (Sandbox Code Playgroud)

不幸的是,当我尝试这个时,$ rows总是空的.但是,如果我将SQL复制到phpMyAdmin中,并将'%keyword%'替换为每个?符号,它工作正常(我使用关键字时得到结果).

我也尝试了以下代码:

$statement = $this->db->prepare("select * from whatever where title like :titleKeyword or author like :authorKeyword");
$statement->bindValue(":titleKeyword",  '%'.$titleKeyword.'%',  PDO::PARAM_STR);
$statement->bindValue(":authorKeyword", '%'.$authorKeyword.'%', PDO::PARAM_STR);
$statement->execute();
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
Run Code Online (Sandbox Code Playgroud)

我在另一个问题中读过,你应该在绑定参数时包含%,而不是在SQL本身(预先准备好的语句)中,但这不起作用.

我可以直接将关键字插入到SQL中(在进行一些清理之后),但我想坚持使用预准备语句.任何帮助将不胜感激.

ste*_*fen 3

这实际上对我有用:

$stmt = $pdo->prepare("select * from t where c like ?");
$stmt->execute(array("70%"));
print_r($stmt->fetchAll());
Run Code Online (Sandbox Code Playgroud)

您使用什么 PHP 版本?