How to prevent SQL Injection in Wordpress?

2020-02-12 05:18发布

问题:

I'm currently using the following query to get values in mysql using php:

The code is working, but now I'm worried about sql injections.

How to prevent SQL injection?

<?php include_once("wp-config.php");
@$gameid = $_GET['gameid'];

global $wpdb;
$fivesdrafts = $wpdb->get_results( 
    "
    SELECT ID
    FROM $wpdb->posts
    WHERE  ID = ".$gameid." 

    "
);
?>

is this safe?

<?php include_once("wp-config.php");
@$gameid = mysql_real_escape_string($_GET['gameid']);

global $wpdb;
$fivesdrafts = $wpdb->get_results(
$wpdb->prepare(
    "
    SELECT ID
    FROM $wpdb->posts
    WHERE  ID = %d", ".$gameid.")
);
?>

回答1:

From the WordPress Codex on protecting queries against SQL Injection attacks:

<?php $sql = $wpdb->prepare( 'query' , value_parameter[, value_parameter ... ] ); ?>

If you scroll down a bit farther, there are examples.

You should also read the database validation docs for a more thorough overview of SQL escaping in WordPress.