If you want to sort a record set on the bases of a particular field either ascending or descending order then used "order by" clause
PHP MySQL ORDER BY Clause Example:
If you want to sort a record set on the bases of a particular field either ascending or descending order then used "order by" clause. For ascending order use asc and for descending order used desc.
Syntax:
SELECT column_name FROM table_name ORDER BY column_name ASC|DESC
Example:
<?php
$connection = mysql_connect("localhost","root","root");
if (!$connection) {
die('PHP Mysql database connection could not connect : ' . mysql_error());
}
else{
$db_name = "php_mysql";
mysql_select_db($db_name, $connection);
$sql = "select * from user order by user_name desc;";
$records = mysql_query($sql, $connection);
while($rows = mysql_fetch_array($records)){
echo "User Id : " . $rows['user_id'] . "<br />";
echo "User Name : " . $rows['user_name'] . "<br />";
echo "User Email : " . $rows['user_email'] . "<br />";
echo "User Address : " . $rows['user_address'] . "<br /><br />";
}
}
mysql_close($connection);
?>
Before running this example the database user table data is:

After running this example the output display in descending order.
Output:
User Id : 6 User Name : Ravi User Email : ravi@gmai.com User Address : Kanpur User Id : 2 User Name : Brijesh User Email : brijesh@gmail.com User Address : Delhi User Id : 3 User Name : Brijesh User Email : brijeshkumar@gmail.com User Address : Delhi User Id : 4 User Name : Avanish User Email : avanish@gmail.com User Address : New Delhi User Id : 5 User Name : Avanish User Email : avanish@gmail.com User Address : New Delhi

[ 0 ] Comments