May 11, 2021 PHP
ORDER BY keywords are used to sort data in a record set.
ORDER BY keywords are used to sort data in a record set.
ORDER BY keywords sort records in ascending order by default.
If you want to sort in descending order, use the DESC keyword.
To learn more about SQL, visit our SQL tutorial.
The following example picks up all the data stored in the Persons table and sorts the results according to the Age column:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br>";
}
mysqli_close($con);
?>
The above results will output:
You can sort by more than one column. When sorted by more than one column, the second column is used only if the values of the first column are the same: