WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/esc sql

Description

Prepares a string for use as an SQL query. This function is a glorified addslashes() that works with arrays.

In 99% of cases, you can use $wpdb->prepare() instead, and that is the recommended method. This function is only for use in those rare cases where you can't easily use $wpdb->prepare(). One example is preparing an array for use in an IN clause.

Note: Be careful to use 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.

Usage

 <?php esc_sql$sql ); ?> 

Parameters

$data
(string|array) (required) An unescaped string or array that needs to be put into a SQL statement.
Default: None

Return Value

(string|array) 
Escaped value appropriate for use in a SQL query, within quotes (as a string). Notably, this result is NOT safe for use in an SQL statement without quotes surrounding it.

Example

<?php

$name   = esc_sql( $name );
$status = esc_sql( $status );

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

?>

Notes

  • $wpdb->prepare() is generally preferred as it corrects some common formatting errors.
  • This function was formerly just an alias for $wpdb->escape(), but that function has now been deprecated.
  • It should be noted that this function will only escape values to be used in strings in the query, as shown in the above example. That is, it only provides escaping for values that will be within quotes (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}.

Change Log

Since: 2.8.0

Source File

esc_sql() is located in wp-includes/formatting.php.

Related

like_escape(), tag_escape(), urlencode(), urlencode_deep()

See: Data Validation article for an in-depth discussion of input and output sanitization.

See also index of Function Reference and index of Template Tags.
This article is marked as in need of editing. You can help Codex by editing it.