基本上,我使用 HTML 表单和 PHP 连接到 MySQL 数据库,并且我希望用户能够在实际返回结果之前从下拉菜单中选择他们希望如何对结果进行排序。
这是我的表格:
<p>View the complete list of books as sorted by:
<form action="usersort.php" method="post">
<select name="sortby"><option value="book_name">Book Title</option>
<option value="author">Author</option></select>
<input type="submit" name="submit" value="Go"></form></p>
这是我的PHP:
<?php
echo '<table align="center" cellspacing="0" cellpadding="5" width="75%"> <tr>
<td align="left"><b><a href="usersort.php?sort=book_name">Book Name</a></b></td>
<td align="left"><b><a href="usersort.php?sort=author">Author</a></b></td>';
require ('mysqli_connect.php');
$sort = (isset($_GET['sortby'])) ? $_GET['sortby'] : 'books';
switch($sort) {
case 'book_name':
$order_by = 'book_name ASC';
break;
case 'author':
$order_by = 'author ASC';
break;
default:
$order_by = 'book_name ASC';
$sort = 'books';
break;
}
$q = "SELECT (book_name) AS name, (author) AS author, (publisher) AS publisher FROM books ORDER BY $order_by";
$r = @mysqli_query ($dbc, $q);
if ($r) {
echo '<table align="center" cellspacing="3" cellpadding="3" width="75%">
<tr><td align="left"><b>Book Name</b></td><td align="left"><b><Author</b></td></tr>';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{echo '<tr><td align="left">' . $row['name'] . '</td><td align = "left">' . $row['author'] . '</td><td align = "left">' . $row['publisher'] . '</td></tr>';
}
echo '</table>';
mysqli_free_result($r);
} else {
echo 'The current books could not be retrieved.';
echo '<p>' . mysqli_error($dbc) . '<br><br>Query: ' . $q . '</p>';
}
?>
我假设由于我将 HTML 表单中的选择值命名为“sortby”,因此我的 PHP 将检索该值并将其插入“sortby”,但每当我尝试通过表单访问返回时,它总是只使用默认情况在开关状态?有人可以告诉我我做错了什么吗?