lisovaccaro
lisovaccaro

Reputation: 33956

MySQL show results with inverted order?

I need to get the last 5 results, that's why I order them by Date DESC but I need to display the results from older to newer. How can I do this?

$data = mysql_query("SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC LIMIT 5"); 

while($row = mysql_fetch_array( $data )) 
    { 
    print "<img class='badge' title='" . $row['Site'] . "' src='http://getfavicon.appspot.com/http://" . $row['Site'] . "?defaulticon=1pxgif' />";
    }

Upvotes: 1

Views: 1572

Answers (3)

Doctorj
Doctorj

Reputation: 24

$data = mysql_query("
    SELECT * FROM (
        SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC LIMIT 5) 
    t ORDER BY Date
");

Also: Please use mysql_real_escape_string (http://at2.php.net/manual/en/function.mysql-real-escape-string.php) for the variable $user. Depending on where you get that from it could be a security leak through sql injection.

Upvotes: 0

Repox
Repox

Reputation: 15476

You can actually order a second time in the same query.

I assume that you have an auto incrementad id (I'll call it 'EntryId' in this example) and then you hopefully should get what you need?

SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC, EntryId ASC LIMIT 5

Upvotes: 0

sanmai
sanmai

Reputation: 30881

$results = array();
while($row = mysql_fetch_array($data)) {
    $results[] = $row;
}

$results = array_reverse($results);

foreach ($results as $row) {
    echo $row['Site']; // etc
}

Manual link: http://php.net/function.array-reverse.php

Upvotes: 2

Related Questions