![]() |
|
PHP MySQL ORDER BY. Free online PHP and MySQL Web Database Programming Tutorial... |
| Lessons | MySQL ORDER BY |
|
|
The ORDER BY keyword in MySQL is used to sort the data in a recordset. It sorts the records in ascending order by default. If our needs are different, we us the DESC keyword to sort the recordset in descending order. Its syntax follows: SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC Example The following example selects / retrieves all the data from the "Students" table, and sorts the result by the "Age" column in ascending order: <?php $con = mysql_connect("localhost", "adam" ,"ada"); if (!$con) { die('Error connecting database'); }mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Students ORDER BY age"); while($row = mysql_fetch_array($result)) { echo $row['name']; echo " " . $row['age']; echo " " . $row['address']; echo "<br />"; } mysql_close($con); ?> Order by multiple columns Similarly we can order the recordset on more than one column. Its syntax follows: SELECT column_name(s) FROM table_name ORDER BY column1, column2, column3
Next: PHP MySQL Functions
|