【问题标题】:Automatically add parameters to get_results()自动将参数添加到 get_results()
【发布时间】:2021-09-28 18:50:58
【问题描述】:

我想调用方法$wpdb->get_results(), 我需要在 SQL 查询中添加参数(WHERE 子句)。 问题是,我想构建一个通用函数,它将接收一个参数对象并生成一个包含我的参数的 SQL 查询。

例如,如果这是我的基本查询:

$taxis = $wpdb->get_results("SELECT * FROM $table", ARRAY_A); // base query

这些是我的参数:

$params = array(
  'color' => 'blue',
  'model' => 'ford'
);

它将使用以下查询调用 get_results

SELECT * FROM $table WHERE color='blue' AND model='ford';

有没有办法构建具有这种行为的函数?

*注意事项:

  1. 我不知道参数对象中有多少参数,也不知道它们将是哪些参数(这就是为什么它必须是通用的)。

  2. 我知道,(就我而言)我需要的唯一 SQL 子句是 WHERE =

【问题讨论】:

  • 是的,有一种方法(实际上可能不止一种方法)。你可以只使用一个循环和一些字符串连接。尽管显然您需要确保使用准备好的语句和参数来构建查询,以避免 SQL 注入和未转义的数据漏洞 - 这增加了一点复杂性(即在 WHERE 子句的同时构建参数数组)但不是很多.
  • 无论你做什么,请确保在查询中使用$wpdb->prepare(),这是ADyson提到的WordPress准备语句的方式。

标签: php sql wordpress


【解决方案1】:

查看代码 cmets 了解每个步骤中发生的情况:

<?php

// make sure this doesn't come from user input, as it is inserted into the query directly
$tableName = $wpdb->prefix . "yourtable";

$columnWhitelist = array( 'color', 'model' );

$params = array(
    'color' => 'blue',
    'model' => 'ford'
);

// filter param keys by allowed column names defined in $columnWhitelist
$params = array_filter(
    $params,
    function ( $key ) use ( $columnWhitelist )  {
        return in_array( $key, $columnWhitelist );
    },
    ARRAY_FILTER_USE_KEY
);

$whereClauseParts = array();

// put column/value pairs of $params into $placeholderValues array
$placeholderValues = array();
foreach ( $params as $column => $value) {
    $whereClauseParts[] = "`$column` = %s";
    $placeholderValues[] = $value;
}

// put together the WHERE clause with placeholders
$whereClause = implode(' AND ', $whereClauseParts );

// put together the whole query tring
$queryString = "SELECT * FROM `$tableName` WHERE " . $whereClause;

// you can use this to see what your prepared query will roughly look like,
// but with missing single quotes around the values 
// die( vsprintf(
//     $queryString,
//     $placeholderValues
// ) );

$wpdb->get_results(
    $wpdb->prepare(
        $queryString,
        $placeholderValues
    )
);

【讨论】:

  • 首先,非常感谢。您的代码有效,它对我帮助很大!只有一件事 - 在$queryString 中,列名用单引号括起来,这在 SQL 查询中无效,这会导致结果为空。如何修改 for 循环,使其输出不带引号的列名?当前查询字符串:"SELECT * FROM 'wp_taxis' WHERE 'color' = 'blue' AND 'model' = 'Volvo'" 所需查询字符串:"SELECT * FROM 'wp_taxis' WHERE color = 'blue' AND model = 'Volvo'" 再次,非常感谢! @康斯坦丁格罗斯
  • 你说的没错,当然!我是在wordpress上下文之外凭记忆写的,所以我没有看到错误。我更新了代码以直接插入列名。为此,我还实现了一个允许列名检查的白名单,无论如何这是一个好主意。
猜你喜欢
  • 2020-03-05
  • 1970-01-01
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多