2017-02-10 172 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