WordPress at a glance

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...


String/Array. Escaped data


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


#1 Basic Example

$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.

Код esc_sql() WP 5.5.1

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

From tag: esc_ (clean validate sanitize)

More from tag: query

More from category: SQL

vladlu 100vlad.lu
Editors: kama 100
No comments
    Log In . Register