duanjiao4763 2013-02-22 12:28
浏览 24
已采纳

如何在不使用多个页面的情况下以不同方式对mysql表中的内容进行排序?

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.

  • 写回答

2条回答 默认 最新

  • dongxie548548 2013-02-22 12:32
    关注

    Yes, you pass the sort column and direction in the 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";
    

    If you have different queries, just use a switch() statement, and change the query accordingly for each type of order.

    // 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;
    

    One more thing - to generate the URLs you can use this:

    $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>";
        }
    }
    

    This will print all the types with all the possible orders. You should play around with this, you can do some neat, dynamic stuff.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测