Escaping strings for WordPress is something that developers should be doing at any place in which the user can be sending information across the wire to the database.

Core offers some nice API functions for this. But if you’re writing a raw database query using $wpdb (which is something that I recommend only when an API doesn’t offer what’s needed), then there are still options, but you may need to fall back to a native PHP function.

Case in point: mysqli_real_escape_string.

Escaping Strings For WordPress

Before I actually show any code, I want to mention that mysql_escape_string was the function once recommended for things like this.

It’s been deprecated since PHP 4.3.0. From the PHP manual:

Warning This function was deprecated in PHP 4.3.0, and it and the entire original MySQL extension was removed in PHP 7.0.0.

Remember, WordPress requires PHP 5.6 at a minimum. So if you stumble across some article recommending using it, it’s either out of date or incorrect.

An Example

Depending on the nature of what you’re working on, you may never need to use $wpdb. I see it used far more often than is necessary. By that, I mean we can normally get away with WP_Query, WP_User_Query, or a similar API before we need to talk directly to the database.

But let’s say that you’re working with a custom table or a custom set of tables, and you need to retrieve some information from each of them (by using a SELECT and a JOIN).

And let’s say that you have an argument passed into a function that contains a string with special characters. To retrieve results that contain the string or value that contains the string (with a LIKE) then, you need to escape the string.

If you’re wondering why this is necessary, let’s assume for a moment that you’re trying to find a record (or set of records) that contain the substring:

Fox Mulder says “I want to believe.”

The quotations in the string need escaping, otherwise, the value passed as part of the query will prematurely terminate the query. Without the escaping, the query will look like this:

And that won’t work because the quotes prematurely terminate the query.

A Contrived Example

The example above is simple, perhaps even a bit contrived. After all, it’s just retrieving information from the database – it’s not sending any information to it.

Using "I Want To Believe" For Escaping Strings for WordPress Database Queries

Escaping strings for WordPress (or any other platform for that matter) isn’t something to take lightly.

If information isn’t properly escaped and sanitized, it can compromise your database. So if, for whatever reason, you can’t use one of the built-in WordPress functions then make sure you’re properly structuring your queries.

The thing is, this is just scratching the surface of writing safe queries.