Understand WordPress esc_sql(): Escape a SQL statement – WordPress Tutorial

By | May 29, 2020

WordPress esc_sql() function is often used to escape a sql statement. In this tutorial, we will introduce some basic features on it.


WordPress esc_sql() is defined as:

function esc_sql( $data ) {
	global $wpdb;
	return $wpdb->_escape( $data );

which means esc_sql() is the same to  $wpdb->_escape().

How to use esc_sql()

We will use a simple example to show how to use it for wordpress beginners.

$name = "alexa's";
echo esc_sql($name);

Run this code, you will get the result.


Then we can use $name in sql statement safely.

As to sql, we can use esc_sql() to escape some variables.

Here is an example:

"SELECT something FROM table WHERE foo = '$name' and status = '$status'"

Of course, we also can use addslashes() to replace esc_sql().

For example:

"SELECT something FROM table WHERE foo = '$name' and status = '$status'"

They are the same.

Leave a Reply

Your email address will not be published. Required fields are marked *