时间:2021-07-01 10:21:17 帮助过:29人阅读

基本语法
ORDER BY子句的基本语法:
SELECT 字段名 FROM 表名 ORDER BY 字段名 ASC/DESC(升序或降序)
注:在ORDER BY子句中ASC是默认的,可省略,表示升序。【相关视频教程推荐:MySQL视频教程】
使用示例
下面是一个数据表"demo",其中包含三个字段,分别为:name、age、sex。我们通过简单的示例来介绍ORDER BY子句的使用。

1、简单的按照age字段升序排序
<?php
header("content-type:text/html;charset=utf-8");
$link = mysqli_connect("localhost", "root", "", "mydb"); //连接数据库
mysqli_set_charset($link,"utf8");
if($link === false){
die("ERROR: Could not connect. "
. mysqli_connect_error());
}
$sql = "SELECT * FROM demo ORDER BY age";
if($res = mysqli_query($link, $sql)){
if(mysqli_num_rows($res) > 0){
echo "<table>";
echo "<tr>";
echo "<th>name</th>";
echo "<th>age</th>";
echo "<th>sex</th>";
echo "</tr>";
while($row = mysqli_fetch_array($res)){
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['sex'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($res);
} else{
echo "找不到匹配的记录。";
}
} else{
echo "错误:无法执行 $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>输出:

代码说明:
“res”变量存储函数mysql_query()返回的数据。
每次调用mysqli_fetch_array()时,它都会从res()集返回下一行。
while循环用于遍历表“demo”的所有行。
2、使用面向对象方法通过ORDER BY子句降序排序
<?php
header("content-type:text/html;charset=utf-8");
$link = new mysqli("localhost", "root", "", "mydb");
mysqli_set_charset($link,"utf8");
if($link === false){
die("ERROR: Could not connect. "
. mysqli_connect_error());
}
$sql = "SELECT * FROM demo ORDER BY age DESC";
if($res = mysqli_query($link, $sql)){
if(mysqli_num_rows($res) > 0){
echo "<table>";
echo "<tr>";
echo "<th>name</th>";
echo "<th>age</th>";
echo "<th>sex</th>";
echo "</tr>";
while($row = mysqli_fetch_array($res)){
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['sex'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($res);
} else{
echo "找不到匹配的记录。";
}
} else{
echo "错误:无法执行 $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>输出:

以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注Gxl网相关教程栏目!!!
以上就是PHP中如何使用MySQL的ORDER BY子句排序的详细内容,更多请关注Gxl网其它相关文章!