dongxing7530 2013-03-18 14:16
浏览 33
已采纳

循环通过MySql表并使用PHP按特定顺序输出

The below loops through a table in my MySql database and shows all the car records in a table cell that match. I know i can use the ORDER BY command in the MySql query to order by a particular column but how can i place a particular record on top and then list all the remaining matches?

For example i have a simple form before this where the user selects their favourite car ($_POST['user_car']) and the required spec ($_POST['user_spec']) with the $_POST method. So my query shows all records that match the spec selected, but i want the selected car to be at the very top of the list with the remaining to follow.

        $query_params = array( 
            ':spec' => $_POST['user_spec']
        );

        $query = " 
            SELECT 
                *
            FROM 
                table
            WHERE
                spec=:spec
        "; 

        try { 
            $stmt = DB::get()->prepare($query); 
            $stmt->execute($query_params); 
            $rows = $stmt->fetchAll(); 
        }  
        catch(PDOException $ex) {}

        foreach($rows as $row):

            $cell .= '<td>
                          <input type="checkbox" '.$check.' name="spec[]" value="'.$row['id'].'"/><span> '.$row['spec'].'
                      </td>';
        endforeach;
  • 写回答

1条回答 默认 最新

  • duankui6150 2013-03-18 14:23
    关注

    The ORDER BY does not limit you to just column(S) you can put evaluated statements in there too.

            SELECT 
                *
            FROM 
                table
            WHERE
                spec=:spec
            ORDER BY car_name=:user_car DESC, car_name ASC
    

    if users favourite car is 'mini', then the record with car_name of 'mini' will evaluate to 1, and the rest to 0, so it will appear first. The rest of the cars will then be ordered by their name.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP