php - 将 LIKE 运算符与 % 一起用于 PDO 准备语句的关键字搜索

标签 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);

不幸的是,当我尝试这个时,$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);

我在另一个问题中读到,您应该在绑定(bind)参数时包括 %,而不是在 SQL 本身(预准备语句)中,但那不起作用。

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

最佳答案

这实际上对我有用:

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

您使用的 PHP 版本是多少?

关于php - 将 LIKE 运算符与 % 一起用于 PDO 准备语句的关键字搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12929816/

相关文章:

php - 我无法返回 MySQL 数据

php - 如何在mysql中制作具有特定日期范围的报告

php - 正确使用 PDO 创建表单以 POST 到 MySQL 中?

php - 使用没有列别名的 PDO::FETCH_ASSOC 的奇怪 MYSQL 结果

php - 如何从mysql表中获取分数总和

php - 自发送php表单并将mysql数据拉到php中的html

php - 我的 PHP PIL 逊相关系数代码有什么问题

mysql - 使用 phpmyadmin 运行时插入查询语法错误

mysql - Perl 脚本从 mysql 查询创建 xml - 内存不足

javascript - 我将如何停止使用 php 将特定关键字插入到 mysql 表中