我正在尝试使用 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/