gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:05:28 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com