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) desc Descending order, from large to small
## Syntax example:
Category Detailed explanation Basic syntax select field from table order by field sort keyword Example select id,Age from Myguests order by Age desc; Example description Query 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:
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:
To learn more about SQL, please visit our SQL tutorial
<?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>";
}
?>
Course Recommendations
Courseware download
The courseware is not available for download at the moment. The staff is currently organizing it. Please pay more attention to this course in the future~
Students who have watched this course are also learning