esc_sql()WP 2.8.0

Prepares 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. It may be more convenient to use this function in those rare cases where you need to process a separate variable and it is inconvenient 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).

This function is a wrapper for wpdb::_escape() method.

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

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

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.

Return

String|Array. Escaped data

Usage

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

Examples

0

#1 Demo

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

#2 Preparing a string to use in an SQL query

$name = esc_sql( $name );

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

The same using $wpdb->prepare():

$wpdb->get_var( wpdb->prepare(
	"SELECT * FROM table WHERE foo = %s", $name
) );

Notes

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

Changelog

Since 2.8.0 Introduced.

Code of esc_sql() WP 5.9.3

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