1

Ok here's the trick. In the query I'm getting the right results from a table named messages. (Its fetching the last 10 messages ordered by the time inserted in reversed order) here's the query:

$query = mysql_query("SELECT time, username, message
                      FROM messages ORDER BY time DESC LIMIT 10");

And than later those messages are printed inside div via ajax with

while ($item = mysql_fetch_assoc($query)) {
    echo $item['time']." - ".$item['username']." - ".$item['message'];
}

But the printed result I want to print them only in the reversed order. Tip: If I use ASC in the ORDER BY clause I don't get the last inserted messages.

Is this possible to do inside php?

3 Answers 3

7

Store your data & than use array_reverse,

while($row = mysql_fetch_assoc($result)){
    $items[] = $row;
}

$items = array_reverse($items ,true);

foreach($items as $item){
   echo $item['time']." - ".$item['username']." - ".$item['message'];
}
2
  • that was cool, I didn't knew about array_reverse. Marking as answer as soon as possible
    – al1en
    May 4, 2014 at 12:29
  • Thank you very much
    – user9123370
    Mar 11, 2019 at 18:49
2

I would use a subquery personally. Im kinda anal about having my data come out of MySQL exactly how I want it, but the array_reverse method will work fine too. Here is my example:

$query = mysql_query("SELECT * FROM (
                      SELECT time, username, message
                      FROM messages ORDER BY time 
                      DESC LIMIT 10) result 
                      ORDER BY time ASC   
                    ");
1
  • I tried your solution too but I am getting an error "Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in..." EDIT: I got it it was syntax error I found muself. Thanks for answer
    – al1en
    May 4, 2014 at 13:10
1

Use: array_unshift - Prepend one or more elements to the beginning of an array

$items = array();

while($row = mysql_fetch_assoc($result)){
    array_unshift($items,$row);
}

foreach($items as $item){
   echo $item['time']." - ".$item['username']." - ".$item['message'];
}

Heres a useless but quick example. I hope it's still there: Simple example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.