我将数据库的信息输入到我网站上的表格中。当我点击下面的链接时,我对表格进行排序,但是我想通过再次点击相同的链接撤消排序。
我怎么做?我研究了rsort
& unsset
但我无法获得解决方案。
例如,我有一个带有tableheader" firstname"的表。其中包含所有名称。当我点击" firstnames"时,它会对第一个名称进行排序。
$sqli = "SELECT * FROM data_base"
if ($_GET['sort'] == 'firstname')
{
$sqli .= " ORDER BY firstname ASC";
}
<th><a href=\"test.php?sort=firstname\">Firstname</a></th>
答案 0 :(得分:1)
根据点击的内容,链接必须不同:
if ($_GET['sort'] == 'firstname')
{
$sqli .= " ORDER BY firstname ASC";
}
else if ($_GET['sort'] == 'lastname ')
{
$sqli .= " ORDER BY lastname ASC";
}
if ($_GET['sort'] == 'firstname'){
echo '<a href=\"test.php\">Firstname</a>';
}
else {
echo '<a href=\"test.php?sort=firstname\">Firstname</a>';
}
if ($_GET['sort'] == 'lastname'){
echo '<a href=\"test.php\">Lastname</a>';
}
else {
echo '<a href=\"test.php?sort=lastname\">Lastname</a>';
}
答案 1 :(得分:1)
根据您之前点击的链接
传递参数$sqli = "SELECT * FROM data_base";
$fname="firstname";
$lname="lastname";
if ($_GET['sort'] == 'firstname')
{
$sqli .= " ORDER BY firstname ASC";
$fname="";
}
else if ($_GET['sort'] == 'lastname')
{
$sqli .= " ORDER BY lastname ASC";
$lname="";
}
echo "<a href=\"test.php?sort=$fname\">Firstname</a>";
echo "<a href=\"test.php?sort=$lname\">Lastname</a>";
答案 2 :(得分:0)
我推荐一种新方法:
向表中添加ID列并将其用作主键,这可以是您的默认排序。 它在数据库级别而不是php级别(例如:数组)的排序更好。
Link1:默认排序
Link2:按FirstName排序
Link3:按姓氏排序
此外,您可以在同一链接中使用ASC和DESC来对ASCending或DEScending进行排序。
答案 3 :(得分:0)
session_start();
$sqli = "SELECT * FROM data_base"
if ($_GET['sort'] == 'firstname'){
if(!isset($_SESSION['first']))//checks if there is a no session
{
$sqli .= " ORDER BY firstname ASC";//sorting
$first='1';
$_SESSION['first']=$first;//start a session
}
if(isset($_SESSION['first']))//checks if their is a session
{
$sqli .= ""; //no sorting
unset($_SESSION['first']); destroys the session so next time it will sort the results
}
}
else if ($_GET['sort'] == 'lastname ')
{
if(!isset($_SESSION['first'])) //checks if there is a no session
{
$sqli .= " ORDER BY lastname ASC"; //sorting
$first='1';
$_SESSION['last']=$last; //start a session
}
if(isset($_SESSION['last'])) //checks if their is a session
{
$sqli .= ""; //no sorting
unset($_SESSION['last']);
}
}
<a href=\"test.php?sort=firstname\">Firstname</a>
<a href=\"test.php?sort=lastname\">Lastname</a>
你可以通过会话添加session_start(); 刚刚过去的顶部