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

Works based on: wpdb::_escape()

No Hooks.

Return

String/Array. Escaped data

Usage

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

Examples

#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->get_var(
	$wpdb->prepare( "SELECT something FROM table WHERE foo = %s and status = %s", $name, $status )
);

Notes

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

Code of esc sql: wp-includes/formatting.php WP 5.2.1

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

Related Functions

From tag: esc_ (clean validate sanitize)

More from tag: query

More from category: SQL

vladlu 100
Editors: kama 100
No comments
    Hello, !     Log In . Register