本文介绍了Wpdb prepare 被错误地调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想准备我的数据以避免 SQL 注入.所以我当前的工作代码显示表列中的数据列表:

全局$wpdb;$sliders = $wpdb->get_results('SELECT alias, title FROM wp_revslider_sliders', ARRAY_A);echo '';如果($滑块){foreach($sliders as $slide){echo '<option value="'.$slide['alias'].'" '.($select_revslider_shortcode == $slide['alias'] ? 'selected=""' : '').'>'.$slide['title'].'</option>';}}回声'</选择>';

我需要使用 $wpdb->prepare 来确保我的数据正确地从数据库中获取.我目前的进展:

$sliders = $wpdb->query($wpdb->prepare("SELECT id, alias, title FROM wp_revslider_sliders", ARRAY_A));

这不起作用.我收到通知:

注意:wpdb::prepare 调用不正确.的查询参数wpdb::prepare() 必须有一个占位符.

谁能告诉我我的代码哪里错了?

问候

解决方案

prepare 方法用于防止 SQL 注入.当您想在查询中插入变量时,您会使用它.它接受占位符,例如用于字符串的 %s、用于整数的 %d 和用于浮点数的 %f.

您的查询没有任何变量,因此您不需要准备方法.您看到一个错误,因为您没有使用任何占位符.

https://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection

I want to prepare my data to avoid SQL Injections. So my current working code to show a list of data from a table's column:

global $wpdb;
$sliders = $wpdb->get_results('SELECT alias, title FROM wp_revslider_sliders', ARRAY_A);

echo '<select name="revslider">';
if ($sliders) {
    foreach($sliders as $slide){
        echo '<option value="'.$slide['alias'].'" '.($select_revslider_shortcode == $slide['alias'] ? 'selected=""' : '').'>'.$slide['title'].'</option>';
    }
}
echo '</select>';

I need to use $wpdb->prepare to be sure that my datas are correctly brought from the db. My current progress:

$sliders = $wpdb->query($wpdb->prepare("SELECT id, alias, title FROM wp_revslider_sliders", ARRAY_A));

This isn't working. I get a notice:

Can anyone tell me where I'm wrong with my code?

Regards

解决方案

The prepare method is used to protect against SQL injection. You'd use it when you want to insert variables into your query. It accepts placeholders such as %s for string, %d for integers and %f for floats.

Your query doesn't have any variables so you don't need the prepare method. You're seeing an error because you aren't using any placeholders.

https://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks

这篇关于Wpdb prepare 被错误地调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 17:02