首页 > 解决方案 > 如何在 wpdb 中编写正确的查询

问题描述

我的查询有什么问题?

$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);
  }

标签: phpmysqlwordpress

解决方案


你应该使用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]));
}

推荐阅读