在mysql中,order by子句可与select语句一起使用,以便按顺序对特定字段的数据进行排序;它可以按升序或降序对结果集进行排序。下面我们来带大家简单了解一下在php中使用mysql的order by子句排序的基本方法,希望对大家有所帮助。

基本语法
ORDER BY子句的基本语法:
SELECT 字段名 FROM 表名 ORDER BY 字段名 ASC/DESC(升序或降序)
注:在ORDER BY子句中ASC是默认的,可省略,表示升序。【相关视频教程推荐:MySQL视频教程】
使用示例
立即学习“PHP免费学习笔记(深入)”;
下面是一个数据表"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);
?>输出:

以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注php中文网相关教程栏目!!!
以上就是PHP中如何使用MySQL的ORDER BY子句排序的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号