php - 如何在 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);
}
解决方案
你应该使用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]));
}
推荐阅读
- node.js - 使用 express 和 nginx 为集群模式配置 pm2?
- android - 片段中按钮的空指针异常
- javascript - 当数字在变量中时,无法将类型创建为特定数字
- reactjs - 刷新/重新加载页面后如何保持 React Material UI 多选的输入值?
- kotlin - 标题不显示在 tablayout KOTLIN
- javascript - 使用 angular.js 预先选择的值
- azure - Azure AD 来宾用户遇到双重 MFA
- java - 获取 IllegalArgumentException:带有 SealedObject 的空输入缓冲区
- sql - 统计符合 SQL 条件的组数
- unity3d - 为什么没有创建 IRtcEngine 实例?