The ORDER BY keyword is used to sort the data in the recordset.
ORDER by keyword
The ORDER BY keyword is used to sort the data in the recordset.
The ORDER BY keyword defaults to sorting the records in ascending order.
If you want to sort in descending order, use the DESC keyword.
Grammar
SELECT column_name (s) from Table_nameorder by column_name (s) asc| DESC
Instance
The following instance selects 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 connectionif (Mysqli_connect_errno () {echo "Failed to connect to MySQL:"). Mysqli_connect_error ();} $result = Mysqli_query ($con, "select * from Persons ORDER by age") and while ($row = Mysqli_fetch_array ($result)) {echo $row [' Fi Rstname '];echo "". $row [' LastName '];echo "". $row [' Age '];echo ' <br> ';} Mysqli_close ($con);? >
The above results will be output:
Glenn Quagmire 33Peter Griffin 35
Sort by two columns
You can sort by more than one column. When sorting by more than one column, the second column is used only when the first column has the same value:
SELECT column_name (s) from Table_nameorder by Column1, Column2
Related reading:
PHP Programming Notes Sharing-very practical
PHP MySQL Order by