如果有的话,什么时候应该使用$ wpdb-> prepare? [英] When should I use $wpdb->prepare, if at all?
问题描述
我很难确定是否应该在WordPress的数据库查询中使用$wpdb->prepare
来防止诸如SQL注入之类的事情.
I have a hard time figuring out if I should be using $wpdb->prepare
on my database queries in WordPress to prevent things such as SQL injection.
$ wpdb Codex 显示了一些使用$ wpdb- >准备函数,以及其他未使用它的示例.
The $wpdb Codex shows some examples using the $wpdb->prepare function, and other examples not using it.
此外,在StackOverflow上的此答案中,有人提到诸如$wpdb->prepare
相同的安全级别.但是其他$wpdb
函数(例如$wpdb->get_var
或$wpdb->query
)又如何呢?
Also, in this answer on StackOverflow, someone mentioned that a function such as $wpdb->insert
has the same level of safety as using $wpdb->prepare
. But what about other $wpdb
functions such as $wpdb->get_var
or $wpdb->query
?
如果什么时候应该使用$wpdb->prepare
?
When should I use $wpdb->prepare
, if at all?
一些我的(简化的)$wpdb
类和函数用法如下:
Some of my (simplified) $wpdb
class and function usage looks like this:
示例1: $wpdb->insert
$wpdb->insert(
'special_posts',
array(
'title' => $title,
'selftext_html' => $selftext_html,
'selftext' => $selftext,
),
array(
'%s',
'%s',
'%s',
)
);
示例2: $wpdb->get_results
$wpdb->get_results("SELECT * FROM special_posts WHERE selftext_html = '$value'");
示例3: $wpdb->get_var
$wpdb->get_var("SELECT title FROM special_posts ORDER BY id DESC LIMIT 1");
示例4: $wpdb->query
$wpdb->query('TRUNCATE TABLE special_posts');
推荐答案
据我了解-具有查询参数占位符($wpdb->insert()
,$wpdb->update()
,$wpdb->delete()
)的方法不需要$wpdb->prepare()
方法,它们已经安全了.
As I understand - the methods those have placeholders for query parameters ($wpdb->insert()
, $wpdb->update()
, $wpdb->delete()
) don't need the $wpdb->prepare()
method, and they are already safe.
但是其他的-那些没有占位符的,需要额外的SQL转义.
But the others - those don't have placeholders, need additional sql escaping.
这篇关于如果有的话,什么时候应该使用$ wpdb-> prepare?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!