【问题标题】:how to write correct query in wpdb如何在 wpdb 中编写正确的查询
【发布时间】:2020-02-08 05:40:41
【问题描述】:

我的查询有什么问题?

$query = "SELECT * FROM wp_posts WHERE post_status = 'publish' AND post_title LIKE '%".$searchKey."%'";

在这种情况下,查询工作正常:

SELECT * FROM wp_posts WHERE post_status = 'publish' AND post_title LIKE '%hello%'

当我尝试向查询中添加变量时,它不起作用

 public function search_result($searchKey)
  {
    $query = "SELECT * FROM wp_posts WHERE post_status = 'publish' AND post_title LIKE '%".$searchKey."%'";
    return $this->wpdb->get_results($query);
  }

【问题讨论】:

  • 您能详细说明“不起作用”是什么意思吗?

标签: php mysql wordpress


【解决方案1】:

您应该使用prepare 方法。

public function search_result($searchKey)
{
    $searchKey = '%'.$searchKey.'%';
    $query = "SELECT * FROM wp_posts WHERE post_status = 'publish' AND post_title LIKE %s";
    return $this->wpdb->get_results($this->wpdb->prepare($query, [$searchKey]));
}

【讨论】:

    猜你喜欢
    • 2021-01-16
    • 2020-05-24
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多