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.

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。