wordpress 如何使用$wpdb->Prepare for dynamic value

qxgroojn  于 11个月前  发布在  WordPress
关注(0)|答案(1)|浏览(174)

我从数组中构建了一个动态值的sql。我如何使用占位符或动态条件?
我这样调用这个函数:get_all_results("TABLE_NAME", ["column" => "VALUE"])

public static function get_all_results(string $table_name, array $where = []): array
    {
        global $wpdb;

        /**
         * Prepare condition
         * 
         * @var string
         */
        $condition = "";
        $index = 0;
        foreach ($where as $key => $value) {
            if ($index > 0) {
                $condition .= "AND ";
            }

            $condition .= "`$key` = '$value' ";
            $index += 1;
        }

        if (!empty($condition)) {
            $condition = " WHERE $condition ";
        }

        $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i {$condition} ", $table_name));
        return $results;
    }

字符串
如何在函数中使用$wpdb->prepare,或者在这种情况下我应该怎么做?
这一行是我的主要问题,“插件检查”-插件给我这个错误。

$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i {$condition} ", $table_name));
WordPress.DB.PreparedSQL.InterpolatedNotPrepared Line 238 of file includes/classes/DB.php.
Use placeholders and $wpdb->prepare(); found interpolated variable $condition at "SELECT * FROM %i WHERE $condition".

"SELECT * FROM %i WHERE $condition",

的数据

vwkv1x7d

vwkv1x7d1#

我将为$where数组中的每个值使用占位符,在下面的代码中,包括为每个条件使用占位符动态构建SQL查询,而不是直接将条件字符串插入查询中。然后这些占位符的实际值安全地通过$wpdb->prepare(),这有效地防止了SQL注入漏洞,希望这对您有所帮助

public static function get_all_results(string $table_name, array $where = []): array
{
    global $wpdb;

    //Prepare a condition
    $condition = "";
    $values = [];
    foreach ($where as $key => $value) {
        if (!empty($condition)) {
            $condition .= " AND ";
        }

        $condition .= $wpdb->prepare("`$key` = %s", $value);
    }

    if (!empty($condition)) {
        $condition = " WHERE $condition ";
    }

    $query = "SELECT * FROM `$table_name` $condition";

    $results = $wpdb->get_results($query);
    return $results;
}

字符串

相关问题