sanitize_sql_orderby

Ensures a string is a valid SQL 'order by' clause.

Description

(string|false) sanitize_sql_orderby( (string) $orderby ); 

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().

Returns (string|false)

Returns $orderby if valid, false otherwise.

Parameters (1)

0. $orderby (string)
Order by clause to be validated.

Usage

  1. if ( !function_exists( 'sanitize_sql_orderby' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // Order by clause to be validated. 
  5. $orderby = ''; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = sanitize_sql_orderby($orderby); 
  9.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/formatting.php  
  1. function sanitize_sql_orderby( $orderby ) { 
  2. 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 ) ) { 
  3. return $orderby; 
  4. return false;