How to prevent SQL injection in WordPress?

SQL injection happens when user input becomes a part of a SQL command. To prevent it in WordPress:

  • Use the built in functions first: WP_Query, get_posts(), get_option(), update_post_meta(). They are safe.
  • When you write SQL with $wpdb, always use $wpdb->prepare() with %s, %d and %f.
  • Use $wpdb->insert(), update() and delete(), which prepare the values for you.
  • For a list inside IN (...), build the placeholders yourself.
global $wpdb;
$bad = "x' OR '1'='1";
echo "Unsafe:  SELECT ID FROM {$wpdb->posts} WHERE post_title = '$bad'\n";
echo 'Prepared: ' . $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s", $bad );
Output

Unsafe: SELECT ID FROM wp_posts WHERE post_title = 'x' OR '1'='1'
Prepared: SELECT ID FROM wp_posts WHERE post_title = 'x\' OR \'1\'=\'1'

In the unsafe query the quote ends the text, and the rest OR '1'='1' becomes SQL. In the prepared one, the quote is escaped, so the whole input is only a value. See WordPress $wpdb.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.