PHP MySQL Order By
Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008
0
The ORDER BY is a keyword which is used to arrange or sort the data in a recordset.
If you will not specify in which order to arrange the result, ORDER BY will arrange them in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.
Syntax
-
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
<?php
$conn = mysql_connect(”localhost”,”tutor”,”tutor123″);
if (!$conn)
{
die(’Could not connect: ‘ . mysql_error());
}
mysql_select_db(”my_db”, $conn);
$result = mysql_query(”SELECT * FROM Country ORDER BY Country”);
while($row = mysql_fetch_array($result))
{
echo $row['Country'];
echo ” ” . $row['Capital'];
echo “<br />”;
}
mysql_close($conn);
?>
Poland Warsaw
Zimbabwe Harare
Order by Two Columns
It is also possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are same:
-
SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
