【发布时间】:2012-10-17 08:07:52
【问题描述】:
我正在尝试使用 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 中(在进行一些清理之后),但我想坚持使用准备好的语句。任何帮助将不胜感激。
【问题讨论】:
-
刚刚做了一个快速的模拟并且工作正常(PHP 5.3.5)~你肯定想在绑定值时添加你的
%。您的 $titleKeyword 和 $authorKeyword 可能有问题? -
不幸的是,没有。我在这里发帖之前检查了这些。
标签: php mysql pdo prepared-statement sql-like