esc_sql()
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().
You can pass an array to the function, then each value of the array will be processed by that function.
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().
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.
No Hooks.
Return
String|Array
. Escaped data, in the same type as supplied.
Usage
esc_sql( $data );
- $data(string|array) (required)
- Unescaped data.
Examples
#1 Demo
echo esc_sql( 'Hello!' ); // Hello! echo esc_sql( 'text "' ); // text \" echo esc_sql( "text ' quote <tag> =" ); // text \' quote = echo esc_sql( "`some_db_1`.table_2_name" ); // `some_db_1`.table_2_name var_dump( esc_sql( 123 ) ); // string(3) "123"
#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. |
esc_sql() esc sql code WP 6.7.1
function esc_sql( $data ) { global $wpdb; return $wpdb->_escape( $data ); }