我在按列标题对数据表进行排序时遇到问题。
我的网站上有一个构建查询机制,可以接受用户选择的 1 个或多个值。这些值被转换为 PHP 变量,然后传递到查询中并将数据表打印到屏幕上。地址栏 URL 也会更新。
我希望能够按表格的列标题进行排序。
我将向您展示绕过整个构建查询函数的 PHP 代码。我将从 SORT 部分和查询开始:
<?php
if ($_GET['sort'] == "") {
$sort_by = "BOL_NUMBER";
} else {
$sort_by = $_GET['sort'];
}
$select = "";
if ($_SESSION['where'] != "") {
$select = "SELECT * FROM `mainTable` WHERE (". $_SESSION['where'] . ") ORDER BY " . $sort_by . "";
}
// $_SESSION['where'] comes from the build query and can contain 1 or more values
$QueryResult = mysql_query($select) or die ();
$resnum = mysql_num_rows($QueryResult);
下一部分是填充表格的地方:
if ($resnum == 0) {
echo "no results";
} else {
echo "<table>\n";
echo "<thead><tr>" .
"<th>BOL</th>" .
"<th>CONTAINER</th>" .
"<th>LOCATION</th>" .
"<th>STATUS</th>" .
"</tr></thead><tbody>\n";
while(($Row = mysql_fetch_assoc($QueryResult)) !== FALSE) {
echo "<tr>";
echo "<td>{$Row[BOL_NUMBER]}</td>";
echo "<td>{$Row[CONTAINER_NUMBER]}</td>";
echo "<td>{$Row[LOCATION_CITY]}</td>";
echo "<td>{$Row[STATUS_TYPE]}</td>";
echo "</tr>";
}
echo "</tbody></table>\n";
?>
还有更多的列。我刚选了几个。
我为下一部分找到了这个页面:
Sorting html table with a href and php from sql database
所以我尝试将我在链接中阅读的内容应用到标题中,如下所示:
"<th><a href='myPage.php?sort=BOL_NUMBER'>BOL</a></th>" .
"<th><a href='myPage.php?sort=CONTAINER_NUMBER'>CONTAINER</a></th>" .
"<th><a href='myPage.php?sort=LOCATION_CITY'>LOCATION</a></th>" .
"<th><a href='myPage.php?sort=STATUS_TYPE'>STATUS</a></th>" .
现在,我可以点击列标题,但当我点击时,它不会保留用户的选择,我可以分辨出来,因为 URL 会像下面这个例子那样变化:
(这只是一个例子,不包括上表中的参数) (只需记下此网址中的 &sort)
http://home.someCompany.com/myAPP/mypage.php?direction=I&type=&submit=Go&city=&pod=&terminal=&ramp=&container=&bol=&voyage=&conStatus=&con_location=&sort=&status=
将更改为此(如果我为 CONTAINER 选择 header ):
http://home.someCompany.com/myAPP/mypage.php?&sort=CONTAINER_NUMBER
发生这种情况时,数据表不再显示在屏幕上。就像它从查询中删除了所有内容,只是添加了排序。但现在没有什么可排序的。
最佳答案
$_SERVER['QUERY_STRING']
超全局变量使您可以访问 GET
参数。通过使用它,您可以保留请求的当前参数。
所以通过这个改变你的链接:
$urlQuery = str_replace(array('&sort=BOL_NUMBER', '&sort=CONTAINER_NUMBER', '&sort=LOCATION_CITY', '&sort=STATUS_TYPE'), '', $_SERVER['QUERY_STRING']); // To clean previous sorting, maybe replace by a regex
"<th><a href='myPage.php?' . $urlQuery . '&sort=BOL_NUMBER'>BOL</a></th>" .
"<th><a href='myPage.php?' . $urlQuery . '&sort=CONTAINER_NUMBER'>CONTAINER</a></th>" .
"<th><a href='myPage.php?' . $urlQuery . '&sort=LOCATION_CITY'>LOCATION</a></th>" .
"<th><a href='myPage.php?' . $urlQuery . '&sort=STATUS_TYPE'>STATUS</a></th>" .
你应该达到你的目标。
关于PHP 按列标题问题排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25388061/