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 trialNils Garland
18,416 PointsReversing 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
22,989 PointsHey 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
22,989 PointsLogan R
22,989 PointsIt's most likely
id
isn't a valid column. I am not sure what columns you have in your table. I would try changingid
todate
and seeing if that fixes the issue.Nils Garland
18,416 PointsNils Garland
18,416 PointsYes that's what I thought, I managed to fix it, thanks though!
Logan R
22,989 PointsLogan R
22,989 PointsNo problem! Glad I could help