How to prevent SQL injection in Wordpress?

I am currently using the following query to get values ​​in mysql using php:

The code works, 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." 

    "
);
?>

safely?

<?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.")
);
?>
+4
source share
1 answer

From WordPress Codex to Protect Queries from SQL Injection Attacks :

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

If you scroll down a bit, there are examples .

You should also read the database validation docs for a more detailed look at SQL leak in WordPress.

+10
source

All Articles