如何使用链接在表中按字母顺序排序列并使用PHP和MySQL?

时间:2016-05-31 01:08:08

标签: php html mysql

我有一张桌子。在表格中,有标题customerID,名称,城市,地址。它们位于表格的顶部,它们是指向同一页面的链接。

我想要做的是,如果我在表格中按名称,它会将所有名称按顺序放入列中;与customerID相同,如果我按下链接,它将订购列中的所有数字。

我希望你们能帮忙。

<html>
<head>
</head>
<body>
<?php
    $options = array(
        PDO::MYSQL_ATTR_INIT_COMMAND=> 'SET NAMES utf8',
    );
    $dsn        = 'mysql:host=localhost;dbname=name';
    $password   = 'pass';
    $username   = 'name';
    $db         = new PDO($dsn, $username, $password, $options);

    $query  = "SELECT";
    $stmt   = $db->prepare($query);
    $stmt->execute();

    echo "<table border=2>";
    echo "<tr>";
        echo "<th><a href="mypage.php?sort=customerid">Customer ID:      </a></th>";
        echo "<th><a href="mypage.php?sort=name">Name:</a></th>";
        echo "<th><a href="mypage.php?sort=city">City:</a></th>";
        echo "<th><a href="mypage.php?sort=address">Address:</a>     </th>";
    echo "</tr>";

    while($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        echo "<tr>";
            $customerid     =$row['customerid'];
            $name           =$row['name'];
            $city           =$row['city'];
            $address        =$row['address'];

            echo "<td>Customer ID: $customerid</td>"; 
            echo "<td>$name</td>";
            echo "<td>$city</td>";
            echo "<td>$address</td>";
        echo "</tr>";
    }   
    echo "</table>";
?>      


   

1 个答案:

答案 0 :(得分:0)

我认为你需要这样的东西:

if(isset($_GET['sort'])){
    $sort = $_GET['sort'];
}

$stmt = $db->prepare("SELECT * FROM myTable ORDER BY :sort");