[英]Sort columns by clicking headers in HTML/PHP/SQL
我的代码只能按特定的列排序一次,但是我无法使其循环遍历asc,desc和default。 现在,我可以单击一次标题并将其排序,按一下后,每次单击都无济于事。 我希望第一次单击以对desc进行排序,然后希望其次单击以对asc进行排序,然后再次单击以返回默认值(按ID asc排序),然后循环浏览这些内容。 这是我到目前为止的内容,有人可以帮助改善我的排序吗? 我不完全了解这是如何工作的,但似乎无法将$ sort设置为desc。 我不知道如何在第三次单击时将其重置为默认值。
$field='ID';
$sort='ASC';
$sortOrder='';
$sortISBN='ISBN';
$sortAuthor='Author';
$sortTitle='Title';
if(isset($_GET['sorting']))
{
if($_GET['sorting']=='ASC')
{
$sort='DESC';
$sortOrder=' ↓';
}
else
{
$sort='ASC';
$sortOrder=' ↑';
}
}
if(isset($_GET['field']))
{
if($_GET['field']=='ISBN')
{
$field='ISBN';
$sortISBN='ISBN ' . $sortOrder;
}
elseif($_GET['field']=='Author')
{
$field='Author';
$sortAuthor='Author ' . $sortOrder;
}
elseif($_GET['field']=='Title')
{
$field='Title';
$sortTitle='Title ' . $sortOrder;
}
}
这是代码的其他相关部分:
<?php
$query=mysql_query("select * from Books order by $field $sort") or die(mysql_error());
echo'<table border="1">';
?>
<tr><th colspan="5">Your book list</th>
<td>
<form name="New" action="new.php" method="POST">
<input type="submit" name="New" value="New" title="Add a new entry"/>
</form>
</td>
</tr>
<tr>
<th></th>
<th><a href="index.php?sorting='.$sort.&field=ISBN"><?php echo $sortISBN; ?></th>
<th><a href="index.php?sorting='.$sort.&field=Author"><?php echo $sortAuthor; ?></th>
<th><a href="index.php?sorting='.$sort.&field=Title"><?php echo $sortTitle; ?></th>
<th></th><th></th>
</tr>
<?php
问题是由于以下三行,
<th><a href="index.php?sorting='.$sort.&field=ISBN"><?php echo $sortISBN; ?></th>
<th><a href="index.php?sorting='.$sort.&field=Author"><?php echo $sortAuthor; ?></th>
<th><a href="index.php?sorting='.$sort.&field=Title"><?php echo $sortTitle; ?></th>
那不是应该在HTML中使用PHP变量的方式。 以上几行应如下所示:
// your code
<th><a href="index.php?sorting=<?php echo $sort ?>&field=ISBN"><?php echo $sortISBN; ?></th>
<th><a href="index.php?sorting=<?php echo $sort ?>&field=Author"><?php echo $sortAuthor; ?></th>
<th><a href="index.php?sorting=<?php echo $sort ?>&field=Title"><?php echo $sortTitle; ?></th>
// your code
旁注:请不要使用mysql_
数据库扩展名,它们从PHP 5.5开始不推荐使用,并且在PHP 7.0中已全部删除。 请改用mysqli
或PDO
扩展名。 这就是为什么您不应该使用mysql_*
函数的原因 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.