Using ORDER BY in $wpdb

If I query the database using this code, I get an array of 4 objects as expected.

global $wpdb;
$rows = $wpdb->get_results("SELECT * FROM ppm_playlists");
var_dump($rows); die();

But if I query using this, I get an empty array.

Read More
global $wpdb;
$rows = $wpdb->get_results("SELECT * FROM ppm_playlists ORDER BY sort-order ASC");
var_dump($rows); die();

Is there a “trick” to using “ORDER BY” in the database class that I am missing in the documentation?

Thanks in advance.

Related posts

Leave a Reply

2 comments

  1. Replace sort-order ASC to sort_order ASC

    When having problems like this it helps to put the problematic query in the phpMyAdmin to locate the problem.

  2. The reason the query failed is because sort-order is interpreted as sort - order (subtracting the column named order from the column named sort). If you wish to keep the hyphen in your column name, you would have to wrap the column in backticks:

    SELECT * FROM ppm_playlists ORDER BY `sort-order` ASC;
    

    Note, however, that using hyphens in column names is not recommended.