通过单击 HTML/PHP/SQL 中的 headers 对列进行排序

Sort columns by clicking headers in HTML/PHP/SQL

我让我的代码按特定列排序一次,但我无法让它在 asc、desc 和 default 之间循环。现在我可以单击 header 一次,它会按 desc 排序,但之后的每次单击都不会执行任何操作。我希望第一次单击按降序排序,然后单击按升序排序,然后单击返回默认值(按 ID 升序排序),然后循环浏览这些。到目前为止,这是我所拥有的,任何人都可以帮助改进我的排序吗?我不完全理解这是如何工作的,但似乎我无法将 $sort 设置为 desc。我不知道如何在第三次点击时将其重置为默认值。

$field='ID';
$sort='ASC';
$sortOrder='';
$sortISBN='ISBN';
$sortAuthor='Author';
$sortTitle='Title';
if(isset($_GET['sorting']))
{
    if($_GET['sorting']=='ASC')
    {
        $sort='DESC';
        $sortOrder=' &#8595';
    }
    else 
    {
        $sort='ASC';
        $sortOrder=' &#8593';
    }
}
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 中已被弃用,并在 [=26= 中被完全删除] 7.0。请改用 mysqliPDO 扩展名。 And this is why you shouldn't use mysql_* functions.