That’s not what esc_sql
is for, or what it should be used for.
Safely Escaping Variables In SQL Queries
To make variables safe for an SQL query, use $wpdb->prepare
, e.g.
$table_name = "{$wpdb->prefix}myTable";
$myID = 12;
$wpdb->query(
$wpdb->prepare(
"UPDATE `$table_name` SET `your_column_1` = 1 WHERE `$table_name`.`your_column_id` = %d",
$myID
)
);
Notice that $myID
is safely inserted into the SQL query using $wpdb->prepare
, and is not directly included in the query string. esc_sql
is not used here.
Safely Escaping Query Results
To escape data you have retrieved from the database on output, use the function that matches the context it’s being displayed in
esc_html
for non-HTML textesc_attr
for HTML tag attributesesc_url
for URLswp_kses_post
for content with tags allowed in post content
When Should I Use esc_sql
?
Very, very, rarely:
Usually you should prepare queries using wpdb::prepare(). Sometimes, spot-escaping is required or useful. One example is preparing an array for use in an IN clause.
and
Be careful in using this function correctly. It will only escape values to be used in strings in the query. That is, it only provides escaping for values that will be within quotes in the SQL (as in field = ‘{$escaped_value}’). If your value is not going to be within quotes, your code will still be vulnerable to SQL injection. For example, this is vulnerable, because the escaped value is not surrounded by quotes in the SQL query: ORDER BY {$escaped_value}. As such, this function does not escape unquoted numeric values, field names, or SQL keywords.
https://developer.wordpress.org/reference/functions/esc_sql/
Most WP developers will never use or encounter esc_sql
and that’s a good thing.