PHP | MySQL ORDER BY 子句
ORDER BY子句可以与 SELECT 语句一起使用,以有序的方式对特定字段的数据进行排序。它用于按升序或降序对结果集进行排序。
句法 :
Order By 子句的基本语法是——
按条款排序的实施:
让我们考虑下表“数据”,其中包含“名字”、“姓氏”和“年龄”三列。
要按升序对 Data 表中的 FirstName 列进行排序,可以使用以下代码。
使用程序方法按条款排序:
0){
echo "";
echo "";
echo "Firstname ";
echo "Lastname ";
echo "age ";
echo " ";
while($row = mysqli_fetch_array($res)){
echo "";
echo "" . $row['Firstname'] . " ";
echo "" . $row['Lastname'] . " ";
echo "" . $row['Age'] . " ";
echo " ";
}
echo "
";
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);
?>
输出 :
代码说明:
- “res”变量存储函数mysql_query()返回的数据。
- 每次调用mysqli_fetch_array()时,它都会返回res()集合中的下一行。
- while 循环用于循环遍历表“数据”的所有行。
使用面向对象的方法按子句排序:
connect_error);
}
$sql = "SELECT * FROM Data ORDER BY Firstname";
if($res = $mysqli->query($sql)){
if($res->num_rows > 0){
echo "";
echo "";
echo "Firstname ";
echo "Lastname ";
echo "Age ";
echo " ";
while($row = $res->fetch_array()){
echo "";
echo "" . $row['Firstname'] . " ";
echo "" . $row['Lastname'] . " ";
echo "" . $row['Age'] . " ";
echo " ";
}
echo "
";
$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 "Firstname ";
echo "Lastname ";
echo "Age ";
echo " ";
while($row = $res->fetch()){
echo "";
echo "" . $row['Firstname'] . " ";
echo "" . $row['Lastname'] . " ";
echo "" . $row['Age'] . " ";
echo " ";
}
echo "
";
unset($res);
} else{
echo "No matching records are found.";
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. "
. $e->getMessage());
}
unset($pdo);
?>
输出 :