WordPress SQL Injection Prevention: Stop Attacks Before They Reach Your Database

Query card showing 1 OR 1=1 changing a query, and a prepared statement keeping input as data

SQL injection (SQLi) means an attacker slips database commands into a form field, URL parameter or API request that your site then runs as part of a query. A successful hit can read your wp_users table, expose customer records or create a hidden admin account.

WordPress core is hardened. Most real-world WordPress SQLi comes from plugins and themes that build queries from unsanitized input, such as an orderby parameter passed straight into SQL.

Use prepared statements

Never concatenate user input into a query. Use $wpdb->prepare(), which keeps the query structure separate from the values.

Unsafe:

$id = $_GET['id'];
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} WHERE ID = $id" );

Safe:

$id = $_GET['id'];
$results = $wpdb->get_results(
  $wpdb->prepare( "SELECT * FROM {$wpdb->posts} WHERE ID = %d", $id )
);
PlaceholderType
%dInteger
%sString
%fFloat

With %d, an input like 1 OR 1=1 is cast to a number and cannot change the query.

Validate and sanitize input

InputFunction
Post IDabsint()
Email (check)is_email()
Plain textsanitize_text_field()
Email (clean)sanitize_email()
Slug or keysanitize_key()
URL you will storeesc_url_raw()

Treat $_GET, $_POST, $_REQUEST and REST input as untrusted. Sanitizing sits in front of prepared statements. It does not replace them.

Keep everything updated

  • Turn on automatic minor core updates.
  • Review plugin and theme updates weekly.
  • Read changelogs for “security” or “escaping” fixes.
  • Delete plugins you no longer use. Inactive code can still be reached by a direct request.

Check plugins before you install

  • Look up the plugin in a public vulnerability database.
  • Check when it last shipped an update.
  • Skip plugins that have not been updated in a year.

Filter attacks before PHP

A firewall can block SQL injection signatures such as UNION SELECT and stacked queries before WordPress loads the vulnerable code. The Hide My WP Ghost security firewall does this at the request level. It covers the gap between a plugin flaw being found and a patch being released.

Lock down the database

  • Give the WordPress database user only the privileges it needs.
  • Use a custom table prefix instead of wp_.
  • Keep wp-config.php out of public reach.
  • Keep regular backups.

Quick checklist

  • Use $wpdb->prepare() for every query.
  • Validate and sanitize input.
  • Update core, plugins and themes.
  • Delete unused plugins.
  • Add a firewall.
  • Restrict database privileges.

FAQ

Is WordPress core vulnerable to SQL injection?

Rarely. Most cases come from plugins and themes.

Is a custom table prefix enough?

No. It only makes blind guessing harder. Prepared statements are the fix.

Do I need a firewall if my code is clean?

Yes, for third-party code you cannot audit.