MYSQLi Order By


ORDER BY keyword is used to sort the data in the recordset

Keywords used for sorting:


Keywords     Description
AscAscending order, from small to large (default)
Desc Descending in descending order, from large to small
Grammar example:


Category      Detailed explanation
Basic grammarSelect field from table order by field sort key words
Example  Select id,Age from Myguests order by Age desc;
Example descriptionQuery the id, Age field in the Myguests table, sorted in descending order

To learn more about SQL, visit our SQL tutorial.

Instance

Let's sort the fields Age in the Myguests table in descending order.

<?php
 Header("Content-type:text/html;charset=utf-8"); //Set the encoding
 $servername = "localhost";
 $username = "root";
 $password = "root";
 $dbname = "test";
 $con=mysqli_connect($servername, $username, $password, $dbname);
 / / Check the connection
 If (mysqli_connect_errno())
 {
     Echo "Connection failed: " . mysqli_connect_error();
 }
 
 $result = mysqli_query($con,"SELECT * FROM MyGuests
 ORDER BY Age DESC ");
 
 While($row = mysqli_fetch_array($result))
 {
     Echo "id"."---".$row['id']."----". $row['firstname'] . "----" . $row['lastname'] ." ----".$row['email']."----".$row['Age'];
     Echo "
";
 }
 ?>
 

Result set limit


Just like the example above, if we don't want the data to show too much, we can use the limit limit.

Instance

Sort the data in the Myguests table in ascending order, showing only 5

<?php 
Header("Content-type:text/html;charset=utf-8"); //Set the encoding
 $servername = "localhost";
 $username = "root";
 $password = "root";
 $dbname = "test";
 $con=mysqli_connect($servername, $username, $password, $dbname);
 / / Check the connection
 If (mysqli_connect_errno())
 {
     Echo "Connection failed: " . mysqli_connect_error();
 }
 
 $result = mysqli_query($con,"SELECT * FROM MyGuests
 ORDER BY Age asc limit 5 ");
 
 While($row = mysqli_fetch_array($result))
 {
     Echo "id"."---".$row['id']."----". $row['firstname'] . "----" . $row['lastname'] ." ----".$row['email']."----".$row['Age'];
     Echo "
";
 }
 ?>
 

 

Last Updated: 2018-07-06 12:32:44 By akshay

SHARE THIS

share_facebook share_twitter share_google_plus

Please Comment Here :