按日期/价格排序

时间:2017-03-12 17:15:59

标签: php

当用户点击按日期排序的链接或按价格排序时,我想显示按日期时间或价格排序的数据库记录。我应该在查询中添加条件吗?

 $sql = "SELECT p.title AS Title, p.date_published) AS Datetime , p.price   AS Price, c.name AS Category FROM products p

           INNER JOIN categories c
              ON c.id = p.category
           INNER JOIN brands b
              ON b.id = p.brand
              .
              .
              .
    ";

    if (isset($_GET['search'])){

          $locations = array();
          $getters = array();
          $queries = array();

          foreach($_GET as $key => $value) {
          .
          .
          .
          }

          if (!empty($brands)) {
            $brd_q = implode(",",$brands);
          }

          if(!empty($getters)) {

            foreach($getters as $key => $value){
              ${$key} = $value;
              switch($key) {
                case 'search':
                array_push($queries, "(p.title LIKE '%$search%' || p.description LIKE '%$search%' || p.number LIKE '%$search%')");
                break;
                case 'scategory':
                array_push($queries, "p.category = $scategory");
                break;
                case 'sbrands':
                array_push($queries, "p_brd.brand_id IN ($brd_q)");
                break;
                .
                .
                .
              }
           }
        }
         
         if(!empty($queries)) {
             $sql .= " WHERE ";
             $i=1;
             foreach($queries as $query) {
                 if ($i < count($queries)) {
                     $sql .= $query." AND ";
                 }else{
                     $sql .= $query;
                 }
                 $i++;
             }

         }
        
          $sql .= " ORDER BY Datetime DESC";
      } 

2 个答案:

答案 0 :(得分:1)

你已经有了这个条款:

$sql .= " ORDER BY Datetime DESC";

您只需要在查询中添加订购参数,在您的白名单订单中将$_GET['order']称为整数索引(从1开始),其中符号指向订单方向。

$orders = ['Datetime', 'Price'];

if (empty($_GET['order'])) $_GET['order'] = -1; // set default order

$index = abs($_GET['order'])-1;
$ord = isset($orders[$index]) ? $orders[$index] : $orders[0];
$direction = $_GET['order'] > 0 ? 'ASC' : 'DESC';

$sql .= " ORDER BY {$ord} {$direction}";

答案 1 :(得分:0)

以简单的方式,您只能使用if else条件进行排序查询。根据你的情况这样。

$sql = "Rest of the Query..";
if($_GET['order'] == 'price') {
   $sql .= " ORDER BY Price DESC";
} else {
   $sql .= " ORDER BY Datetime DESC";
}

当用户点击按价格或日期时间排序时,将根据条件执行查询。

(OR)

您可以更新查询案例条件,如下例所示。

ORDER BY 
CASE WHEN "price" = $_GET['order'] THEN price END DESC,
CASE WHEN "datetime" = $_GET['order'] THEN datetime END DESC

(or)

ORDER BY 
CASE $_GET['order'] 
WHEN "price" THEN price END DESC,
WHEN "datetime" THEN datetime END DESC

etc...

无论您选择什么样的展位都将具有相同的性能和效率。