我有一张桌子。在表格中,有标题customerID,名称,城市,地址。它们位于表格的顶部,它们是指向同一页面的链接。
我想要做的是,如果我在表格中按名称,它会将所有名称按顺序放入列中;与customerID相同,如果我按下链接,它将订购列中的所有数字。
我有
if ($_POST['sort'] == 'customerid') {
$query .= " ORDER BY customerid";
} elseif ($_POST['sort'] == 'name') {
$query .= " ORDER BY name";
} elseif ($_POST['sort'] == 'city') {
$query .= " ORDER BY city";
} elseif ($_POST['sort'] == 'address') {
$query .= " ORDER BY address";
}
但我不确定它在代码中的意义,所以任何帮助都会非常感激
我希望你们能帮忙。
<html>
<head>
</head>
<body>
<?php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$dsn = 'mysql:host=localhost;dbname=agmarcel';
$password = 'asdf';
$username = 'agmarcel';
$db = new PDO($dsn, $username, $password, $options);
$query = "SELECT";
if ($_POST['sort'] == 'customerid') {
$query .= " ORDER BY customerid";
} elseif ($_POST['sort'] == 'name') {
$query .= " ORDER BY name";
} elseif ($_POST['sort'] == 'city') {
$query .= " ORDER BY city";
} elseif ($_POST['sort'] == 'address') {
$query .= " ORDER BY address";
}
$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>";
?>
</body>
</html>
答案 0 :(得分:2)
更改$query = "SELECT"
到
$query = "SELECT * from your tablename";
if ($_POST['sort'] == 'customerid')
{
$query .= " ORDER BY customerid";
}
elseif ($_POST['sort'] == 'name')
{
$query .= " ORDER BY name";
}
elseif ($_POST['sort'] == 'city')
{
$query .= " ORDER BY city";
}
elseif($_POST['sort'] == 'address')
{
$query .= " ORDER BY address";
}