esc_sql()
云策文档标注
概述
esc_sql() 函数用于转义数据以在 MySQL 查询中使用,通常建议优先使用 wpdb::prepare() 进行查询准备。该函数仅转义在 SQL 字符串引号内的值,不适用于未加引号的数值、字段名或 SQL 关键字。
关键要点
- esc_sql() 转义数据用于 MySQL 查询,但主要用于字符串值在引号内的情况。
- 从 WordPress 4.8.3 起,'%' 字符会被替换为占位符字符串,以防止某些 SQL 注入攻击,这可能影响代码的预期行为。
- 函数参数 $data 可以是字符串或数组,返回转义后的相同类型数据。
- 使用 esc_sql() 时需谨慎,因为它不转义未加引号的数值、字段名或 SQL 关键字,可能导致 SQL 注入漏洞。
- 推荐使用 $wpdb->prepare() 替代,因为它能纠正一些常见的格式化错误。
- esc_sql() 原是 $wpdb->escape() 的别名,但后者现已弃用。
代码示例
$name = esc_sql( $name );
$status = esc_sql( $status );
$wpdb->get_var( "SELECT something FROM table WHERE foo = '$name' and status = '$status'" );注意事项
esc_sql() 仅适用于值在 SQL 引号内的情况(如 field = '{$escaped_value}'),否则代码仍易受 SQL 注入攻击。例如,ORDER BY {$escaped_value} 是脆弱的,因为转义值未在查询中用引号包围。
原文内容
Escapes data for use in a MySQL query.
Description
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.
NOTE: Since 4.8.3, ‘%’ characters will be replaced with a placeholder string, this prevents certain SQLi attacks from taking place. This change in behavior may cause issues for code that expects the return value of esc_sql() to be usable for other purposes.
Parameters
$datastring|arrayrequired-
Unescaped data.
Source
function esc_sql( $data ) {
global $wpdb;
return $wpdb->_escape( $data );
}
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |
Skip to note 3 content
J.D. Grimes
It should be noted that this function 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..Skip to note 4 content
Codex
Basic Example
get_var( "SELECT something FROM table WHERE foo = '$name' and status = '$status'" ); ?>