2017-02-10 213 views
0

我有一個php表格顯示mysql表格中的數據。按字母順序排列數據

現在該表已按部門按字母順序排列,但每個部門內的用戶都不是。

在下面的示例中,您將看到部門按字母順序排列,但每個部門下的用戶數據不是。例如,

      Admin Department 
       Wade  3234234  [email protected] 
       George  3434323  [email protected] 
          Workshop Department 
       Zyiad  45454523 [email protected] 
       Buffy  48282191 [email protected] 

我的代碼:

<center> 
<html> 
<head> 
<title>Extension List</title></head><body> 
<br> 
<h1> Alpine Motors Extension List</h1> 
<h2><a href="add.php">Add Extension</a> 
<br> 
<br> 
<form action="AlpineExtensionList.php" method='post'> 
<input type="submit" value="Print PDF"/> 
<br> 
<br> 
<a href="delete.php"> Delete Extension</a></h2> 
<br> 
<br> 
<?php 
$db_host = 'localhost'; 
$db_user = 'root'; 
$db_pwd = '*****'; 

$database = 'list'; 
$table = 'users'; 

$conn = mysqli_connect($db_host, $db_user, $db_pwd) or die("Connecting to database failed"); 

mysqli_select_db($conn, $database) or die("Can't select database"); 

// sending query 
$result = mysqli_query($conn, "SELECT name, email, extension, phone, department FROM {$table} ORDER BY department ASC"); 
if (!$result) { 
    die("Query to show fields from table failed"); 
} 

echo "<table border='1'><tr>"; 

// printing table rows 
$temp = ""; 

while($row = mysqli_fetch_array($result)) 
{ 
    echo "<tr>"; 

    if ($row['department'] != $temp){ 
     echo "<td colspan='4' style='text-align: center; font-weight: bold'>{$row['department']}</td></tr>\n<tr>"; 
     $temp = $row['department']; 
    } 

    echo "<td>" . $row['name'] . "</td><td>" . $row['email'] . "</td><td>" . $row['extension'] . "</td><td>" . $row['phone'] . "</td>"; 

    echo "</tr>\n"; 
} 
// sending query 
$result = mysqli_query($conn, "SELECT name, email, extension, phone, department FROM {$table} ORDER BY department ASC"); 
if (!$result) { 
    die("Query to show fields from table failed"); 
} 

echo "<table border='1'><tr>"; 

// printing table rows 
$temp = ""; 

while($row = mysqli_fetch_array($result)) 
{ 
    echo "<tr>"; 

    if ($row['department'] != $temp){ 
     echo "<td colspan='4' style='text-align: center; font-weight: bold'>{$row['department']}</td></tr>\n<tr>"; 
     $temp = $row['department']; 
    } 

    echo "<td>" . $row['name'] . "</td><td>" . $row['email'] . "</td><td>" . $row['extension'] . "</td><td>" . $row['phone'] . "</td>"; 

    echo "</tr>\n"; 
} 
mysqli_free_result($result); 
echo "</table>" 
?> 
</h2> 
</body> 
</html> 
</center> 
+0

可複製http://stackoverflow.com/questions/514943/php-mysql-order-by-two-來訂購吧列 – m7md

+0

這不是我的問題先生 – RedZ

回答

3

目前你只是排序方式department

ORDER BY department 

如果你想通過額外的字段順序,添加這些領域。例如:

ORDER BY department, name 
+0

ty先生我不知道我可以設置他們兩個 – RedZ

0

你必須通過部門及姓名

ORDER BY department, name