Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Reversing data shown from database

So I am creating a simple post section and I wan't to make sure that the latest posts are from the top to bottom. Right now tho when I add a new post it is shown att the bottom. Is there any way of reversing this somehow? Here is my code.

<?php
$sql = "SELECT * FROM posts";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()) {
    echo "<div class='panel panel-default'>
    <div class='panel-heading'>";
    echo $row['date'];
    echo"</div> <div class='panel-body'>";
    echo $row['message'];
    echo "</div> </div>";
}
?>

Please keep in mind that although this might not be the most attractive code, I am still a beginner to PHP.

1 Answer

Logan R
Logan R
22,989 Points

Hey Nils!

You can actually do this in your SQL request.

Take a look at your following line of code:

$sql = "SELECT * FROM posts";

In SQL, just like the SELECT keyword, there is a keyword called ORDER BY. The arguments are: ORDER BY column ASC|DESC.

`DESC` - Higher to lower
`ASC` - Lower to higher

You are able to append this to the end of your query, making it:

SELECT * FROM posts ORDER BY id DESC

If you have any further questions about anything, feel free to reply!

Logan R
Logan R
22,989 Points

It's most likely id isn't a valid column. I am not sure what columns you have in your table. I would try changing id to date and seeing if that fixes the issue.

Yes that's what I thought, I managed to fix it, thanks though!

Logan R
Logan R
22,989 Points

No problem! Glad I could help