我正在尝试构建这个准备好的声明:
$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/