php mysqli 使用通配符准备语句

标签 php mysql prepared-statement

我正在尝试构建这个准备好的声明:

$sql = "SELECT * FROM entries WHERE";
$sql .= " title LIKE ? OR title LIKE ? OR title LIKE ? OR title LIKE ?";
$sql .= " OR content LIKE ? OR content LIKE ? OR content LIKE ? OR content LIKE ?";

$q = $this->db->prepare($sql);

$one = $this->term;
$two = "%" . $this->term;
$three = $this->term . "%";
$four = "%" . $this->term . "%";

$q->bind_param("ssssssss", $one, $two, $three, $four, $one, $two, $three, $four);
$q->execute();

$this->db 是我的 mysqli 连接对象

$this->term 是用户提供的字符串。

我没有从数据库收到任何类型的错误。我知道 sql 语句有效,我用 $this->db->query() 运行它,结果很好。当我使用准备好的语句运行它时,它没有返回任何结果。有什么建议吗?

最佳答案

要在准备好的语句中使用通配符,您需要在 sql 语句中使用 CONCAT。数据库将负责将百分号连接到您的搜索词上。

假设您希望在搜索词的开头或结尾使用通配符,您的 sql 应如下所示:

$sql = "SELECT * FROM entries WHERE title LIKE CONCAT('%', ?, '%') OR content LIKE CONCAT('%', ?, '%')";

关于php mysqli 使用通配符准备语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6041072/

相关文章:

php - Android 上的 idHTTP Not Acceptable 错误 406

php - 在第二个表 MySQL 上按顺序加入 2 个表时的索引

c++ - 尝试修改 sqlite3 插入以返回 PK。不确定如何具体使用 sqlite3

java - 为什么 Java 将 1h 添加到我的 DateTime 中?

c# - 组合框索引和非连续索引值

python - 如何在Python中使用pyodbc进行参数化查询?

php - 这个字符串替换足以抵御 SQL 注入(inject)攻击吗?

php - 无法在 Laravel 6.5.1 上制作 "composer require laravel/ui --dev"

php - 如何停止循环语句?

mysql - 转换为 UTF 8 后数据库中的特殊字符处理