目录

PHP MySQL 使用 ORDER BY 子句


从 MySQL 数据库中选择和排序数据

ORDER BY 子句用于按升序或降序对结果集进行排序。

ORDER BY 子句默认按升序对记录进行排序。要按降序对记录进行排序,请使用 DESC 关键字。

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

要了解有关 SQL 的更多信息,请访问我们的SQL教程


使用 MySQLi 选择和排序数据

以下示例从 MyGuests 表中选择 id、firstname 和 Lastname 列。记录将按姓氏列排序:

示例(MySQLi 面向对象)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
  }
} else {
  echo "0 results";
}
$conn->close();
?>
运行示例 »

从上面的例子中解释的代码行:

首先,我们设置 SQL 查询,从 MyGuests 表中选择 id、firstname 和 Lastname 列。记录将按姓氏列排序。下一行代码运行查询并将结果数据放入名为 $result 的变量中。

然后,function num_rows()检查返回的行数是否超过零。

如果返回的行数多于零,则该函数fetch_assoc()将所有结果放入一个我们可以循环遍历的关联数组中。这while()循环遍历结果集并输出 id、firstname 和 lastname 列中的数据。

以下示例以 MySQLi 过程方式显示与上面示例相同的内容:

示例(MySQLi 过程)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
  // output data of each row
  while($row = mysqli_fetch_assoc($result)) {
    echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
  }
} else {
  echo "0 results";
}

mysqli_close($conn);
?>
运行示例 »


您还可以将结果放入 HTML 表格中:

示例(MySQLi 面向对象)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  echo "<table><tr><th>ID</th><th>Name</th></tr>";
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
  }
  echo "</table>";
} else {
  echo "0 results";
}
$conn->close();
?>
运行示例 »

使用 PDO 选择数据(+ 准备好的语句)

以下示例使用准备好的语句。

这里我们从 MyGuests 表中选择 id、firstname 和 Lastname 列。记录将按姓氏列排序,并将显示在 HTML 表格中:

示例(PDO)

<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator {
  function __construct($it) {
    parent::__construct($it, self::LEAVES_ONLY);
  }

  function current() {
    return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
  }

  function beginChildren() {
    echo "<tr>";
  }

  function endChildren() {
    echo "</tr>" . "\n";
  }
}

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname");
  $stmt->execute();

  // set the resulting array to associative
  $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
  foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
    echo $v;
  }
} catch(PDOException $e) {
  echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
运行示例 »