sanitize_sql_orderby()
云策文档标注
概述
sanitize_sql_orderby() 函数用于验证字符串是否为有效的 SQL 'ORDER BY' 子句。它接受列名和排序方向,支持 RAND() 函数,并返回验证后的字符串或 false。
关键要点
- 验证 SQL 'ORDER BY' 子句的有效性,确保输入字符串符合安全规范。
- 支持单列或多列,可带 ASC 或 DESC 排序方向,例如 'column_1 ASC, column_2 DESC'。
- 接受 'RAND()' 作为特殊排序参数。
- 参数 $orderby 为必需,函数返回验证后的字符串或 false。
代码示例
function sanitize_sql_orderby( $orderby ) {
if ( preg_match( '/^s*(([a-z0-9_]+|`[a-z0-9_]+`)(s+(ASC|DESC))?s*(,s*(?=[a-z0-9_`])|$))+$/i', $orderby ) || preg_match( '/^s*RAND(s*)s*$/i', $orderby ) ) {
return $orderby;
}
return false;
}
原文内容
Ensures a string is a valid SQL ‘order by’ clause.
Description
Accepts one or more columns, with or without a sort order (ASC / DESC).
e.g. ‘column_1’, ‘column_1, column_2’, ‘column_1 ASC, column_2 DESC’ etc.
Also accepts ‘RAND()’.
Parameters
$orderbystringrequired-
Order by clause to be validated.
Source
function sanitize_sql_orderby( $orderby ) {
if ( preg_match( '/^s*(([a-z0-9_]+|`[a-z0-9_]+`)(s+(ASC|DESC))?s*(,s*(?=[a-z0-9_`])|$))+$/i', $orderby ) || preg_match( '/^s*RAND(s*)s*$/i', $orderby ) ) {
return $orderby;
}
return false;
}
Changelog
| Version | Description |
|---|---|
| 2.5.1 | Introduced. |
Skip to note 2 content
1naveengiri
get_results( implode( ' ', $query ) ); ?>