📜  PHP | MySQL ORDER BY 子句

📅  最后修改于: 2022-05-13 01:55:17.168000             🧑  作者: Mango

PHP | MySQL ORDER BY 子句

ORDER BY子句可以与 SELECT 语句一起使用,以有序的方式对特定字段的数据进行排序。它用于按升序或降序对结果集进行排序。

句法 :
Order By 子句的基本语法是——

按条款排序的实施:

让我们考虑下表“数据”,其中包含“名字”、“姓氏”和“年龄”三列。

要按升序对 Data 表中的 FirstName 列进行排序,可以使用以下代码。

使用程序方法按条款排序:

 0){
        echo "";
            echo "";
            echo "";
            echo "";
            echo "";
            echo "";
        while($row = mysqli_fetch_array($res)){
            echo "";
                echo "";
                echo "";
                echo "";
            echo "";
        }
        echo "
FirstnameLastnameage
" . $row['Firstname'] . "" . $row['Lastname'] . "" . $row['Age'] . "
";         mysqli_free_result($res);     } else{         echo "No matching records are found.";     } } else{     echo "ERROR: Could not able to execute $sql. "                                 . mysqli_error($link); } mysqli_close($link); ?>

输出 :

代码说明:

  1. “res”变量存储函数mysql_query()返回的数据。
  2. 每次调用mysqli_fetch_array()时,它都会返回res()集合中的下一行。
  3. while 循环用于循环遍历表“数据”的所有行。

使用面向对象的方法按子句排序:

connect_error);
}
  
$sql = "SELECT * FROM Data ORDER BY Firstname";
if($res = $mysqli->query($sql)){
    if($res->num_rows > 0){
        echo "";
            echo "";
                echo "";
                echo "";
                echo "";
            echo "";
        while($row = $res->fetch_array()){
            echo "";
                echo "";
                echo "";
                echo "";
            echo "";
        }
        echo "
FirstnameLastnameAge
" . $row['Firstname'] . "" . $row['Lastname'] . "" . $row['Age'] . "
";         $res->free();     } else{         echo "No matching records are found.";     } } else{     echo "ERROR: Could not able to execute $sql. "                                      . $mysqli->error; }    $mysqli->close(); ?>

输出 :

使用 PDO 方法按条款排序:

setAttribute(PDO::ATTR_ERRMODE, 
                        PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " 
                            . $e->getMessage());
}
try{
    $sql = "SELECT * FROM Data ORDER BY Firstname";
    $res = $pdo->query($sql);
    if($res->rowCount() > 0){
        echo "";
            echo "";
                echo "";
                echo "";
                echo "";
            echo "";
        while($row = $res->fetch()){
            echo "";
                echo "";
                echo "";
                echo "";
            echo "";
        }
        echo "
FirstnameLastnameAge
" . $row['Firstname'] . "" . $row['Lastname'] . "" . $row['Age'] . "
";         unset($res);     } else{         echo "No matching records are found.";     } } catch(PDOException $e){     die("ERROR: Could not able to execute $sql. "                                      . $e->getMessage()); }    unset($pdo); ?>

输出 :