简体   繁体   中英

Newest entry first in while loop

I'm building a PM system in PHP, and I have a problem. Every mail, is stored in a database. This query gets all the mails, that were written to the user your logged in as

$getmails = "SELECT * FROM mail WHERE reciever='$drow[ID]'";

Then I have this code, to show every mail, written to the user in a list.

if ($getter->num_rows > 0) {
    while($mrow = $getter->fetch_assoc()) {
        // do something
    }
}

This code works and shows the mails. The problem is, that his code shows the newest mail, at them bottom of the list. And the oldest mail at the top.

Every mail has a ID, and i'm thinking that a way to sort these mails to the newest first, would be to sort after the lowest ID at the top.

Can anyone here help me achieving this? Thanks in advance

Full code:

<div class="mailbox">
<?php
    if ($getter->num_rows > 0) {
        while($mrow = $getter->fetch_assoc()) {
            if($mrow['seen'] == 0) {
                echo "<li><b>$mrow[titel]</b></li>";
            } else {
                echo "<li>$mrow[titel]</li>";
            }   
        }
    } else {
        echo "You have no mails";
    }
?>
</div> 

Sort e-mails by date, I expect column create_date in your table.

$getmails = "SELECT * FROM mail WHERE reciever='$drow[ID]' ORDER BY create_date DESC";

Or using ID, the newest should be the highest:

$getmails = "SELECT * FROM mail WHERE reciever='$drow[ID]' ORDER BY id DESC";

Using the ORDER BY command and picking a column name to sort by would be the easiest.

"SELECT * FROM mail WHERE receiver='$drow[ID]' ORDER BY date DESC"

I'd also recommend including the 'seen' value in your selection to increase efficiency

"SELECT * FROM mail WHERE receiver='$drow[ID]' and seen=0 ORDER BY date DESC"

You should add 'ORDER BY column_name DESC' at the end of your query. This results in retrieving database information in a specific order.

DESC stands for 'DESCENDING'.

Your query should look as follows:

$getmails = "SELECT * FROM mail WHERE reciever='$drow[ID]' ORDER BY ID DESC";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM