PHP MySQL Order By PHP

PHP MySQL Order By  

PHP MySQL Order By

PHP MySQL Order By

The order by clause is used to fetch data in ascending order or descending order on the basis of column.

Let's see the query to select data from emp4 table in ascending order on the basis of name column.

  1. SELECT * FROM emp4 order by name  

Let's see the query to select data from emp4 table in descending order on the basis of name column.

  1. SELECT * FROM emp4 order by name desc  

PHP MySQLi Order by Example

Example

  1. <?php  
  2. $host = 'localhost:3306';  
  3. $user = '';  
  4. $pass = '';  
  5. $dbname = 'test';  
  6. $conn = mysqli_connect($host, $user, $pass,$dbname);  
  7. if(!$conn){  
  8.   die('Could not connect: '.mysqli_connect_error());  
  9. }  
  10. echo 'Connected successfully<br/>';  
  11.   
  12. $sql = 'SELECT * FROM emp4 order by name';  
  13. $retval=mysqli_query($conn, $sql);  
  14.   
  15. if(mysqli_num_rows($retval) > 0){  
  16.  while($row = mysqli_fetch_assoc($retval)){  
  17.     echo "EMP ID :{$row['id']}  <br> ".  
  18.          "EMP NAME : {$row['name']} <br> ".  
  19.          "EMP SALARY : {$row['salary']} <br> ".  
  20.          "--------------------------------<br>";  
  21.  } //end of while  
  22. }else{  
  23. echo "0 results";  
  24. }  
  25. mysqli_close($conn);  
  26. ?>  

Output:

Connected successfully
EMP ID :3
EMP NAME : jai
EMP SALARY : 90000
--------------------------------
EMP ID :2
EMP NAME : karan
EMP SALARY : 40000
--------------------------------
EMP ID :1
EMP NAME : ratan
EMP SALARY : 9000
--------------------------------

Download free E-book of PHP


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries