• in my theme I’ve got a wp_db query which fetches the most recent resut from a table and then sets this as a variable.

    What I would like to be able to do is get the two most recent results and set those as separate variables. How can I go about doing this?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Normally that is done by adding something like this to your query;

    ORDER BY post_date DESC LIMIT 2

    But, that would depend on your query and what table/tables you’re looking at. Can you show us the query that you’re working with?

    Thread Starter mortonc

    (@mortonc)

    Thanks.

    Here’s what I’ve currently got

    <?php
    global $wpdb;
    $heightcm = $wpdb-> get_var("SELECT height FROM group_data WHERE group_id = $group_id 
    
    ORDER BY rowid DESC LIMIT 0,1"
    
    );
    
       // Convert the height to metres and ft
    
       $heightm = ($tideheightcm/100);
       $heightmround = round($tideheightm,1);
    
       $heightft = ($tideheightm*3.281);
       $heightftround = round($tideheightft,1,PHP_ROUND_HALF_DOWN);
    
    ?>

    I couldn’t get it to order by date for some reason so I’m using row_id which is auto incremented.

    So what I would like to be able to do is get the two most recent heights and set them as $heightcm1 and $heightcm2

    Another thing that might be really handy is to have the ‘time’ data for each row as well.

    Well, what’s the date column called in that table? You’ll need to use ORDER BY with that column. Something like this… But this is with guessed column names.

    SELECT
       height,
       data_date
    FROM group_data
    WHERE group_id = $group_id
    ORDER BY data_date DESC LIMIT 2

    That will get the latest two records.

    Thread Starter mortonc

    (@mortonc)

    but how do I then place the results into variables?

    This is the basics for it…

    $results = $wpdb->get_results ($sql);
    
    foreach ($results as $row) {
        echo "<p>Row: '".$row->height."'</p>";
    }

    You’ll have to figure out your own styling and what you want output, but that’s how it’s done.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘wp_db get 2 most recent items’ is closed to new replies.