PHP 基础教程
PHP 高级教程
PHP & MySQL DATABASE
PHP 示例
PHP 参考手册

PHP MySQL ORDER BY 子句

在本教程中,您将学习如何使用 PHP 以升序或降序对 MySQL 表中的数据进行排序和显示。

对结果集进行排序

ORDER BY 子句可以与 SELECT 语句结合使用,以查看按特定字段排序的表中的数据。 ORDER BY 子句允许您定义要排序的字段名称以及升序或降序的排序方向。

该子句的基本语法可以通过以下方式给出:

SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

让我们使用 SELECT 语句中的 ORDER BY 子句进行 SQL 查询,然后我们将通过将其传递给 PHP mysqli_query() 函数来执行此查询以获取有序数据。 考虑 demo 数据库中的以下 persons 表:

+----+------------+-----------+----------------------+
| id | first_name | last_name | email                |
+----+------------+-----------+----------------------+
|  1 | Peter      | Parker    | peterparker@mail.com |
|  2 | John       | Rambo     | johnrambo@mail.com   |
|  3 | Clark      | Kent      | clarkkent@mail.com   |
|  4 | John       | Carter    | johncarter@mail.com  |
|  5 | Harry      | Potter    | harrypotter@mail.com |
+----+------------+-----------+----------------------+

以下示例中的 PHP 代码从 persons 表中选择所有行,并按字母升序按 first_name 列对结果进行排序。

示例

Procedural Object Oriented PDO
Download
<?php
/* 尝试 MySQL 服务器连接。 假设您正在运行 MySQL
具有默认设置的服务器(用户 'root' 没有密码) */
$link = mysqli_connect("localhost", "root", "", "demo");
 
// 检查连接
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 
// 尝试选择查询执行用 order by 子句
$sql = "SELECT * FROM persons ORDER BY first_name";
if($result = mysqli_query($link, $sql)){
    if(mysqli_num_rows($result) > 0){
        echo "<table>";
            echo "<tr>";
                echo "<th>id</th>";
                echo "<th>first_name</th>";
                echo "<th>last_name</th>";
                echo "<th>email</th>";
            echo "</tr>";
        while($row = mysqli_fetch_array($result)){
            echo "<tr>";
                echo "<td>" . $row['id'] . "</td>";
                echo "<td>" . $row['first_name'] . "</td>";
                echo "<td>" . $row['last_name'] . "</td>";
                echo "<td>" . $row['email'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
        // 关闭记录集
        mysqli_free_result($result);
    } else{
        echo "No records matching your query were found.";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
 
// 关闭连接
mysqli_close($link);
?>
<?php
/* 尝试 MySQL 服务器连接。 假设您正在运行 MySQL
具有默认设置的服务器(用户 'root' 没有密码) */
$mysqli = new mysqli("localhost", "root", "", "demo");
 
// 检查连接
if($mysqli === false){
    die("ERROR: Could not connect. " . $mysqli->connect_error);
}
 
// 尝试选择查询执行用 order by 子句
$sql = "SELECT * FROM persons ORDER BY first_name";
if($result = $mysqli->query($sql)){
    if($result->num_rows > 0){
        echo "<table>";
            echo "<tr>";
                echo "<th>id</th>";
                echo "<th>first_name</th>";
                echo "<th>last_name</th>";
                echo "<th>email</th>";
            echo "</tr>";
        while($row = $result->fetch_array()){
            echo "<tr>";
                echo "<td>" . $row['id'] . "</td>";
                echo "<td>" . $row['first_name'] . "</td>";
                echo "<td>" . $row['last_name'] . "</td>";
                echo "<td>" . $row['email'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
        // Free result set
        $result->free();
    } else{
        echo "No records matching your query were found.";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}
 
// 关闭连接
$mysqli->close();
?>
<?php
/* 尝试 MySQL 服务器连接。 假设您正在运行 MySQL
具有默认设置的服务器(用户 'root' 没有密码) */
try{
    $pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
    // 设置 PDO 错误模式为异常
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
 
// 尝试选择查询执行
try{
    $sql = "SELECT * FROM persons ORDER BY first_name";
    $result = $pdo->query($sql);
    if($result->rowCount() > 0){
        echo "<table>";
            echo "<tr>";
                echo "<th>id</th>";
                echo "<th>first_name</th>";
                echo "<th>last_name</th>";
                echo "<th>email</th>";
            echo "</tr>";
        while($row = $result->fetch()){
            echo "<tr>";
                echo "<td>" . $row['id'] . "</td>";
                echo "<td>" . $row['first_name'] . "</td>";
                echo "<td>" . $row['last_name'] . "</td>";
                echo "<td>" . $row['email'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
        // Free result set
        unset($result);
    } else{
        echo "No records matching your query were found.";
    }
} catch(PDOException $e){
    die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
 
// 关闭连接
unset($pdo);
?>

排序结果后,结果集将如下所示:

+----+------------+-----------+----------------------+
| id | first_name | last_name | email                |
+----+------------+-----------+----------------------+
|  3 | Clark      | Kent      | clarkkent@mail.com   |
|  5 | Harry      | Potter    | harrypotter@mail.com |
|  2 | John       | Rambo     | johnrambo@mail.com   |
|  4 | John       | Carter    | johncarter@mail.com  |
|  1 | Peter      | Parker    | peterparker@mail.com |
+----+------------+-----------+----------------------+

提示: 默认情况下,ORDER BY 子句按升序对结果进行排序。 如果要按降序对记录进行排序,可以使用 DESC 关键字。

Advertisements