PHP中如何使用MySQL的ORDER BY子句排序
来源:青灯夜游
发布时间:2019-01-16 14:57:04
阅读量:1322
在MySQL中,ORDER BY子句可与SELECT语句一起使用,以便按顺序对特定字段的数据进行排序;它可以按升序或降序对结果集进行排序。下面我们来带大家简单了解一下在PHP中使用MySQL的ORDER BY子句排序的基本方法,希望对大家有所帮助。

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

1、简单的按照age字段升序排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?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子句降序排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?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);
?>
|
输出:
