When you retrieve data from a database, the rows are returned in the order they were stored. To sort the result-set, you use the ORDER BY clause.
The ORDER BY clause sorts the records in ascending order by default. To sort the records in descending order, you use the DESC keyword.
<?php // Database connection code omitted...// Select all users and sort them alphabetically by their lastname $sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname ASC"; $result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " . $row["lastname"] . "<br>"; } } else { echo "0 results"; } ?>
ORDER BY date DESC: Useful for showing the most recent blog posts or comments at the top of a page.ORDER BY price ASC: Used in e-commerce sites to sort products from lowest price to highest price.Which keyword is used to reverse the default sorting order (from highest to lowest)?