我正在尝试使用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);
不幸的是,当我尝试这个时,$ 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);
我在另一个问题中读过,你应该在绑定参数时包含%,而不是在SQL本身(预先准备好的语句)中,但这不起作用。
我可以直接将关键字插入到SQL中(在进行一些清理之后),但我想坚持使用预准备语句。任何帮助将不胜感激。
这实际上对我有用:
$stmt = $pdo->prepare("select * from t where c like ?");
$stmt->execute(array("70%"));
print_r($stmt->fetchAll());
你使用什么PHP版本?
感谢Steffen和Terry的帮助。
我最终通过切换到bindParam()而不是bindValue()来解决问题。我不知道为什么我不能用bindValue()做到这一点,但是现在我太累了不能去关心。