我找到了一个简单的解决方案,可以对html表中的每一列进行排序。 现在,我还希望能够按desc的每一列进行排序,但由于有解决方案的想法,由于if中有两个if,因此代码看起来很复杂。
我想不出另一种解决方案,它看起来可能更好,整体上也更容易。
这是我现在的代码:
<th><a href="mypage.php?sort=type">Type:</a></th>
<th><a href="mypage.php?sort=desc">Description:</a></th>
<th><a href="mypage.php?sort=recorded">Recorded Date:</a></th>
<th><a href="mypage.php?sort=added">Added Date:</a></th>
<?php
$sql = "SELECT * FROM MyTable";
if ($_GET['sort'] == 'type')
{
$sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
$sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
$sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
$sql .= " ORDER BY DateAdded";
}
$>
我的第一个想法是:
$sql = "SELECT * FROM MyTable";
$checkSort = false;
if ($_GET['sort'] == 'type')
{
if ($checkSort == false)
{
$sql .= " ORDER BY type";
$checkSort = true;
}
if ($checkSort == true)
{
$sql .= " ORDER BY type desc";
$checkSort = false;
}
}
我认为它看起来并不干净,因为我需要为每一列执行此操作,并且将来我的表应成为更多列。
答案 0 :(得分:1)
您可以尝试直接在通话中发送该值。
<th><a href="mypage.php?sort=type&sortType=ASC/DESC">Type:</a></th>
<th><a href="mypage.php?sort=description&sortType=ASC/DESC">Description:</a></th>
<th><a href="mypage.php?sort=daterecorded&sortType=ASC/DESC">Recorded Date:</a></th>
<th><a href="mypage.php?sort=dateadded&sortType=ASC/DESC">Added Date:</a></th>
<?php
$sql = "SELECT * FROM MyTable ORDER BY ".$_GET['sort']." ".$_GET['sortType'];
?>
很明显,当您直接将调用传递给DB时,您必须进行健全性检查。
注意-“&sortType = ASC / DESC”,仅要发送ASC或DESC之一
答案 1 :(得分:1)
我会使用它:(DOC)
$sql = "SELECT * FROM MyTable";
switch($_GET['sort']):
case 'type':
$sql .= " ORDER BY type";
break;
case 'desc':
$sql .= " ORDER BY Description";
break;
case 'recorded':
$sql .= " ORDER BY DateRecorded";
break;
case 'added':
$sql .= " ORDER BY DateAdded";
break;
endswitch;
您可以根据需要添加任意多个“ case”!
答案 2 :(得分:0)