【问题标题】:Using the LIKE operator with % for a keyword search with PDO prepared statements将 LIKE 运算符与 % 一起用于使用 PDO 准备语句的关键字搜索
【发布时间】: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


【解决方案1】:

这实际上对我有用:

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

你使用什么 PHP 版本?

【讨论】:

  • 我使用的是 5.3.1。甚至 PDOStatement 的 PHP 文档中的一些 cmets 也建议使用这两种方法中的一种。
  • 仔细检查变量 $titleKeyword 和 $authorKeyword(使用 var_dump!)
  • 已经完成(这是在一个版本中,我在调用 bindValue 之前和之后修改 var 以具有 %): string(6) "%iPod%" string(6) "%iPod% "
  • 您在 PDO 和 phpMyAdmin 中使用相同的数据库吗?然后启用mysql查询日志(见dev.mysql.com/doc/refman/5.6/en/query-log.html
【解决方案2】:

感谢 Steffen 和 Terry 的帮助。

我最终通过切换到 bindParam() 而不是 bindValue() 自己解决了这个问题。我不知道为什么我不能用 bindValue() 来做,但现在我太累了,根本不在乎。

【讨论】:

猜你喜欢
  • 2012-10-24
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 2011-04-23
  • 2012-02-08
  • 2010-12-19
相关资源
最近更新 更多