0

I am using some filters to display the products. Filters like colors, price and stuff.

Link : http://www.applechain.com/products/iPod.php

I use this query

$sql = "Select * 
  from tbl_product  
  where device='iPhone'  
    and (color='$c1'   
      or color='$c2'    
      or color='$c3'    
      or color='$c4'    
      or color='$c5'    
      or color='$c6'    
      or color='$c7'    
      or color='$c8'    
      or color='$c9'    
      or color='$c10'   
    ) and (storage='$cp1'    
      or storage='$cp2'    
      or storage='$cp3'    
      or storage='$cp4'    
      or storage='$cp5'   
    ) and (f_unlock='$factory')    
    and (warranty='$warranty')    
    and (price >= '$price1'    
      and price <= '$price2'   
    ) 
  order by product_id desc";

I am using the AND condition for main parameters. Now how do I display the result if my only two parameters gets satisfied. How to achieve that if color and storage parameters gets satisfied,it shows result based on them only irrespective of whether the others are selected or not.

4

2 回答 2

0

您可以根据设置的内容构建查询,通常 ORM 工具会为您执行此操作。

由于开始使用 PHP 框架可能为时已晚,您应该执行以下操作:

if(isset($colours))
{
    $sub_query = concatenateOrClauses($colours, 'color');
    $main_query .= $sub_query;
}

private function concatenateOrClauses($values, $name)
{
    $query_string = "";
    for($i = 0; $i < sizeof($values); $i++)
    {
        if($i == 0)
        {
            $query_string = $name."=".$values[$i];
        }
        else
        {
            $query_string = $query_string." OR ".$name."=".$values[$i];
        }
    }
    return $query_string;
}
于 2013-11-18T09:39:09.190 回答
0

简单的。从查询中删除其他条件。

顺便说一句,您可以通过这种方式重写该查询...

SELECT * 
  FROM tbl_product 
 WHERE device = 'iPhone' 
   AND color IN ('$c1','$c2','$c3','$c4','$c5','$c6','$c7','$c8','$c9','$c10')
   AND storage IN ('$cp1','$cp2','$cp3','$cp4','$cp5')
   AND f_unlock = '$factory'
   AND warranty = '$warranty'
   AND price BETWEEN '$price1' and '$price2'
 ORDER 
    BY product_id DESC;
于 2013-11-18T09:37:24.320 回答