When should I use $wpdb->prepare, if at all?

限于喜欢 提交于 2019-12-20 07:28:35

问题


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.

The $wpdb Codex shows some examples using the $wpdb->prepare function, and other examples not using it.

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?

When should I use $wpdb->prepare, if at all?

Some of my (simplified) $wpdb class and function usage looks like this:


Example 1: $wpdb->insert

$wpdb->insert(
                'special_posts', 
                    array( 
                        'title' => $title,
                        'selftext_html' => $selftext_html,
                        'selftext' => $selftext,
                    ), 

                    array(
                        '%s',
                        '%s',
                        '%s',
                    )
            );

Example 2: $wpdb->get_results

$wpdb->get_results("SELECT * FROM special_posts WHERE selftext_html = '$value'");

Example 3: $wpdb->get_var

$wpdb->get_var("SELECT title FROM special_posts ORDER BY id DESC LIMIT 1");

Example 4: $wpdb->query

$wpdb->query('TRUNCATE TABLE special_posts');

回答1:


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.

But the others - those don't have placeholders, need additional sql escaping.



来源:https://stackoverflow.com/questions/37558506/when-should-i-use-wpdb-prepare-if-at-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!