sanitize_sql_orderby( string $orderby ): string|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()’.


Top ↑

Parameters

$orderby string Required
Order by clause to be validated.

Top ↑

Return

string|false Returns $orderby if valid, false otherwise.


Top ↑

Source

File: wp-includes/formatting.php. View all references

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

Top ↑

Changelog

Changelog
Version Description
2.5.1 Introduced.

Top ↑

User Contributed Notes

  1. Skip to note 1 content
    Contributed by 1naveengiri
    <?php 
    //code copied from Woocommerce code base shows a perfect use of this function.
    $orderby           = in_array( $args['orderby'], $allowed_orders, true ) ? $args['orderby'] : 'download_log_id';
    $order             = 'DESC' === strtoupper( $args['order'] ) ? 'DESC' : 'ASC';
    $orderby_sql       = sanitize_sql_orderby( "{$orderby} {$order}" );
    $query[]           = "ORDER BY {$orderby_sql}";
    $raw_download_logs = $wpdb->get_results( implode( ' ', $query ) );
    ?>

You must log in before being able to contribute a note or feedback.