• In my theme I am trying to show a the latest piece of data which is in a custom table.

    The table ‘table_data’ consists of 4 columns: id, date, time, value

    So I’m checking the id against a custom field in my post (‘$id’ which has been set as a variable earlier on) , it then should display the value of the most recent entry. I would like to sort by date and then time.

    I’ve tried

    <?php
    global $wpdb;
    $thisvalue = $wpdb-> get_var("SELECT value FROM table_data WHERE id = $id 
    
    ORDER BY date DESC LIMIT 0,1"
    
    );
    
       // Echo the value
       echo "<strong>Value: </strong>";
       echo $thisvalue;
    ?>

    which prints the value of the first row with the most recent date (which in this case has the earliest time) so it’s not the latest result.

    I’ve tried to do

    <?php
    global $wpdb;
    $thisvalue = $wpdb-> get_var("SELECT value FROM table_data WHERE id = $id 
    
    ORDER BY date,time DESC LIMIT 0,1"
    
    );
    
       // Echo the value
       echo "<strong>Value: </strong>";
       echo $thisvalue;
    ?>

    but that seems to be giving me the oldest value which happens to be from a previous year, changing DESC to ASC makes no difference.

    I also tried

    ORDER BY date,time DESC | DESC LIMIT 0,1"

    and

    ORDER BY date,time DESC, DESC LIMIT 0,1"

    and

    ORDER BY date,time DESC DESC LIMIT 0,1"

    but they then return no values at all.

    All I need to do is show the most recent entry, any help would be really appreciated, I’m sure i’m doing something stupid.

  • The topic ‘WPDB sort by Date and Time from table’ is closed to new replies.