sanitize_sql_orderby()WP 2.5.1

Checks if the provided string can be used in the ORDER BY part of an SQL query.

Accepts one or more columns, with or without sort order (ASC/DESC):

  • column_1.
  • column_1, column_2.
  • column_1 ASC, column_2 DESC.
  • Also understands RAND().

No Hooks.

Returns

String|false. Will return the provided string or false if it does not fit.

Usage

sanitize_sql_orderby( $orderby );
$orderby(string) (required)
The string to check and return if it fits.

Examples

0

#1 Checking ORDER BY part of SQL query

// OK example
$orderby = ' col1 ASC ';
$orderby = sanitize_sql_orderby( $orderby ); // string(10) " col1 ASC "

// ERROR example
$orderby = sanitize_sql_orderby( ' col-1 ASC ' ); // bool(false)

Changelog

Since 2.5.1 Introduced.

sanitize_sql_orderby() code WP 6.8.1

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;
}