How to use MySQLi 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 = mysqli_connect($host,$user,$pass,$dbname) or die(mysqli_error($dbname));
$sql = "SELECT * FROM users order by name ASC";
$retval=mysqli_query($conn,$sql);
if(mysqli_num_rows($retval) > 0){
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Salary</th></tr>";
while($row= mysqli_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";
}
mysqli_close($conn);
?>
id | name | salary |
---|---|---|
1 | Name1 | 55000 |
2 | Name2 | 70000 |
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning