【问题标题】:php mysqli prepared statement using wildcardsphp mysqli 使用通配符准备语句
【发布时间】:2011-05-18 07:07:59
【问题描述】:

我正在尝试构建这个准备好的语句:

$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() 运行它,结果很好。当我使用准备好的语句运行它时,它返回时没有结果。有什么建议吗?

【问题讨论】:

  • 为什么所有的测试都在寻找“sth”、“%sth”、“sth%”或“%sth%”?这将产生与仅查找“%sth%”相同的结果,因此您可以将查询保留为 SELECT * FROM entries WHERE title LIKE '%sth%' OR content LIKE '%sth%'
  • Carlos:感谢您指出这一点。我查看了有关通配符搜索的更多文档,它确实匹配任何内容(包括零匹配)。谢谢。

标签: php mysql prepared-statement


【解决方案1】:

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

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

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

【讨论】:

  • 可以,但你不必这样做。可以像 OP 一样在 PHP 端添加通配符
【解决方案2】:

我无法让它与准备好的语句一起工作。我移至 mysqli->query() 并转义了用户字符串。 Carlos,感谢您帮助我解决了我的问题。

【讨论】:

    猜你喜欢
    • 2014-09-04
    • 2016-07-22
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2013-04-21
    相关资源
    最近更新 更多