按字母顺序排序数据

时间:2017-02-10 13:45:10

标签: php html

我有一个显示mysql表中数据的php表。

现在该表已按部门的字母顺序排列,但每个部门内的用户不是。

在下面的示例中,您将看到部门按字母顺序排列,但每个部门下的用户数据不是。 例如

                           Admin Department 
                Wade        3234234     Wade@acasdaas.com
                George      3434323     George@aasdsasas.com
                          Workshop Department
                Zyiad     45454523    Zyiad@aasdasd.com
                Buffy     48282191    buffy@assad.com

我的代码:

<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>

2 个答案:

答案 0 :(得分:3)

目前您只是按department订购:

ORDER BY department

如果您想按其他字段订购,请添加这些字段。例如:

ORDER BY department, name

答案 1 :(得分:0)

您必须按部门和名称订购

ORDER BY department, name