WordPress at Your Fingertips

esc_sql() WP 2.8.0

Escapes data for use in a MySQL query. Protects against SQL injections. May accept an array of strings for processing.

Works based on addslashes(), but also accepts arrays.

Almost always this function can be replaced with $wpdb->prepare() and such replacement is recommended since it corrects some formatting errors in addition to the escaping. Using esc_sql() may be more convenient in those rare cases when you need to write additional code to use $wpdb->prepare().

Since 4.8.3, % character will be replaced by a placeholder string, this prevents SQLi attacks. This change in function behavior can cause problems when the result of esc_sql() is used further in code. See. [wpdb::add_placeholder_escape()](/function/wpdb:: add_placeholder_escape).

esc_sql() is a wrapper for wpdb::_escape() method.

The function is intended only for processing strings which will then be used in the SQL query inside the quotes: field = '$esc_value' but not field = $esc_value.

If the escaped value is not in the quotes, then an SQL injection can be made. For example, the code ORDER BY $esc_value is dangerous...

1 time — -0.00003 sec (speed of light) | 50000 times — 0.06 sec (speed of light) | PHP 7.4.8, WP 5.6.2

No Hooks.


String|Array. Escaped data


esc_sql( $data );
$data(string|array) (required)
Unescaped data


#1 Demo

echo esc_sql( 'Hello!' ); // Hello!
echo esc_sql( 'text "' );  // text \"
echo esc_sql( "text ' quote <tag> =" );  // text \' quote  =

#2 Preparing a string to use in an SQL query

$name   = esc_sql( $name );
$status = esc_sql( $status );

$wpdb->get_var( "SELECT something FROM table WHERE foo = '$name' and status = '$status'" );

The same using $wpdb->prepare():

	$wpdb->prepare( "SELECT something FROM table WHERE foo = %s and status = %s", $name, $status )


esc_sql() until version 3.6 was an alias of the $wpdb->escape() method which then has been deprecated.


  • Global. wpdb. $wpdb WordPress database abstraction object.


Since 2.8.0 Introduced.

Code of esc_sql() WP 5.8.1

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

esc_ (clean validate sanitize)



vladlu 100vlad.lu
Editors: Kama 100
No comments
    Log In