PHP MySQL Order...LOGIN

PHP MySQL Order By

ORDER BY Keywords are used to sort the data in the record set


Keywords used for sorting:

Keywords Description
asc Sort in ascending order, from small to large (default)
descDescending order, from large to small

## Syntax example:

Basic syntax select field from table order by field sort keyword Exampleselect id,Age from Myguests order by Age desc; Example descriptionQuery the id and Age fields in the Myguests table and sort them in descending order

To learn more about SQL, please visit our SQL tutorial.


##Example

In the following example, let us sort the field Age in the Myguests table in descending order

<?php
 header("Content-type:text/html;charset=utf-8");    //设置编码
 $servername = "localhost";
 $username = "root";
 $password = "root";
 $dbname = "test";
 $con=mysqli_connect($servername, $username, $password, $dbname);
 // 检测连接
 if (mysqli_connect_errno())
 {
     echo "连接失败: " . 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 "<br>";
 }
 ?>

Program running result:

5.png


Result set limit

Just like the above example, If we don't want the data to be displayed too large, we can use limit.

Example

Sort the data in the Myguests table in ascending order and display only 5

<?php
 header("Content-type:text/html;charset=utf-8");    //设置编码
 $servername = "localhost";
 $username = "root";
 $password = "root";
 $dbname = "test";
 $con=mysqli_connect($servername, $username, $password, $dbname);
 // 检测连接
 if (mysqli_connect_errno())
 {
     echo "连接失败: " . 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 "<br>";
 }
 ?>

program running results:

8.png


To learn more about SQL, please visit our SQL tutorial


Next Section

<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "test"; $con=mysqli_connect($servername, $username, $password, $dbname); // 检测连接 if (mysqli_connect_errno()) { echo "连接失败: " . 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 "<br>"; } ?>
submitReset Code
ChapterCourseware
    None
Category Detailed explanation