Jackbeeby Jackbeeby - 2 months ago 16
PHP Question

Reverse Output order

i have an issue, I'm creating a comment page but i want to show all the results upside down so, the last result sent will be closest to the bottom. but i also need a limit of how many comments or messages it shows. I'm using mysqli and php.

$sql = "SELECT id, message FROM messages WHERE name = '$user' ORDER BY id DESC LIMIT 10";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {

echo "<div id='message'>" . $row["message"]. "</div> ";
}
} else {
echo "<p style='color:white;'>No messages have been sent</p>";
}


the problem with this is it shows the messages i have sent last at the top of the page instead of at the bottom

Answer

One option here is to wrap your current query and then change the ordering to ORDER BY id ASC:

$sql = "SELECT t.id, t.message FROM"
       ." (SELECT id, message FROM messages WHERE name = '$user' ORDER BY id DESC LIMIT 10)"
       ." ORDER BY t.id";

For clarity, here is a more readable version of the query:

SELECT t.id,
       t.message
FROM
(
    SELECT id, message
    FROM messages
    WHERE name = '$user'
    ORDER BY id DESC
    LIMIT 10
) t
ORDER BY t.id