1

I have a section on my website where users can post comments. Just above these comments I have 4 links - Oldest, Newest, Top Rated and Worst Rated. Currently I have 4 different pages for each of these links.

oldest.php - sorts the comments by date and time ascending

newest.php - sorts the comments by date and time descending

top.php - sorts the comments depending on how many likes they have

worst.php - sorts the comments depending on how many dislikes they have

They are all being sorted with a mySQL statement such as

$sql = "SELECT * FROM comments ORDER BY date DESC, time DESC LIMIT $offset, $rowsperpage";

I'm just wondering is there any way to order these comments by using just one page instead of having 4 different pages?

Any help would be greatly appreciated.

4

2 回答 2

3

是的,您在 URL 中传递了排序列和方向。

$type = 'new'; // default order
$cols = array('old', 'new', 'worst'); // array with possible options columns, to prevent SQL injection
if (in_array($_GET['type'], $cols) {
    $type = $_GET['type'];
}
$order = (strtolower($_GET['order']) == 'asc')?'ASC':'DESC'; // again - to prevent bad data
$sql = "SELECT * FROM comments ORDER BY {$type} {$order}, time DESC LIMIT $offset, $rowsperpage";

如果您有不同的查询,只需使用一个switch()语句,并为每种类型的订单相应地更改查询。

// use the same order as before
switch ($_GET['type']):
case 'old':
     $sql = " ... ";
break;

// more options
default:
    // default can be used for the most common option, for example when you first enter the page with no type argument in the URL
break;

还有一件事 - 要生成 URL,您可以使用它:

$cols = array('old', 'new', 'worst'); // you can make this array a config variable
$order = array('asc', 'desc');
foreach ($cols as $col) {
    foreach ($order as $ord) {
        echo "<a href='index.php?type={$col}&order={$ord}'>".ucwords($col). ' ' . ucwords($ord)"</a>";
    }
}

这将打印具有所有可能订单的所有类型。你应该玩这个,你可以做一些整洁、动态的东西。

于 2013-02-22T12:32:26.643 回答
1

当然,您可以使用单个页面来管理它。

您可以拥有单页而不是 4 页

评论.php

然后你可以像下面这样为 4 个链接传递 GET 参数

comments.php?type=oldest
comments.php?type=newest
comments.php?type=top
comments.php?type=worst

然后comments.php你可以像下面这样放置条件语句:

$order_by = "ORDER BY date DESC, time DESC"; // Default order
if(isset($_GET["type"]) && $_GET["type"] == "newest")
    $order_by = "ORDER BY date DESC, time DESC";
elseif(isset($_GET["type"]) && $_GET["type"] == "oldest")
    $order_by = "ORDER BY date, time";
elseif(isset($_GET["type"]) && $_GET["type"] == "top")
    ... put your order by here ...
elseif(isset($_GET["type"]) && $_GET["type"] == "worst")
    ... put your order by here ...

然后在 $sql 下面使用

$sql = "SELECT * FROM comments ".$order_by." LIMIT $offset, $rowsperpage";

于 2013-02-22T12:34:56.317 回答