Support

Account

Home Forums General Issues ORDER BY on SELECT not working

Solved

ORDER BY on SELECT not working

  • Hi All,

    I simply cannot work this one out. I’ve got the following code:

    
    			$rows = $wpdb->get_results($wpdb->prepare( 
    			"
    			SELECT * 
    			FROM wp_postmeta
    			WHERE meta_key LIKE %s
    				AND meta_value LIKE %s
    			",
    			'dates_%_available_dates', 
    			''.$year.''.$month.'%' 
    			));
    

    This is used to produce a list of results based on a repeater field which I then use with the date picker to allow one course to have multiple dates. I then list the courses per month. Works a treat! What I need to do, is order the results by date for each month. I therefore thought:

    
    			$rows = $wpdb->get_results($wpdb->prepare( 
    			"
    			SELECT * 
    			FROM wp_postmeta
    			WHERE meta_key LIKE %s AND meta_value LIKE %s",
    			'dates_%_available_dates', ''.$year.''.$month.'%', 			
    			"ORDER BY meta_value ASC"		
    			));	
    

    Would work. Sadly, it doesn’t make a difference. If I run the SQL direct in PHPMyAdmin:

    
    SELECT * 
    FROM  <code>wp_postmeta</code> 
    WHERE  <code>meta_key</code> LIKE  'dates_%_available_dates'
    AND  <code>meta_value</code> LIKE  '201309%'
    ORDER BY meta_value ASC 
    LIMIT 0 , 30

    It works! I cant see it’s the for loop that returns the list as surely that’s dependent on the SQL?

    Am I missing something?

    Thanks in advanced

  • Ok, managed to solve it by swapping the SQl round a little, like so:

    			$rows = $wpdb->get_results($wpdb->prepare( 
    			"
    			SELECT * 
    			FROM wp_postmeta
    			WHERE meta_key LIKE %s AND meta_value LIKE %s ORDER BY meta_value ASC",
    			'dates_%_available_dates', ''.$year.''.$month.'%', 			
    			""		
    			));	
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘ORDER BY on SELECT not working’ is closed to new replies.