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 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100