How to use MySQL Order By
The ORDER BY is a keyword that is used to sort the results based on one or more columns. by default, it sorts the result set in ascending order. if we want to sort the results in descending order we use DESC keyword. for ascending order we use ASC keyword.
The order by clause is used to fetch data in ascending order or descending order on the basis of the column.
Query to select data from users table in ascending order on the basis of name column.
SELECT * FROM users order by name
The query to select data from the users table in descending order on the basis of the name column.
SELECT * FROM users order by name desc
<?php
$host = "localhost";
$user = "";
$pass = "";
$dbname = "users";
$conn = mysql_connect($host,$user,$pass) or die(mysql_error());
if(!$conn){
die("Could not connect:".mysql_connect_error());
}
// select database
mysql_select_db($dbname,$conn);
$sql = "SELECT * FROM users order by name ASC";
$retval=mysql_query($sql);
if(mysql_num_rows($retval) > 0){
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Salary</th></tr>";
while($row= mysql_fetch_array($val))
{
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['salary']."</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo "0 results";
}
mysql_close();
?>
id | name | salary |
---|---|---|
1 | Name1 | 55000 |
2 | Name2 | 70000 |
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning