PHP过滤器组合成一个SQL查询

时间:2017-12-07 13:18:28

标签: php sql

我正在尝试根据访问者的过滤器过滤我的数据库。

$query = "select * from Sheet1 where";

//filter query start 
if (!empty($brand)) {
  $branddata = implode("','", $brand);
  //testing removing query
  $query .= " Brand in('$branddata') and";
}

if (!empty($model)) {
  $modeldata = implode("','", $model);
  //testing removing query
  $query .= " Model in('$modeldata') and";
}

/* if(!empty($model) && empty($brand)){

} */

if (!empty($spower) && !empty($epower)) {
  $query .= " Power>='$spower' and Power<='$epower' and";
}

if (!empty($sprice) && !empty($eprice)) {
  $query .= " Doors>='$sprice' and Doors<='$eprice'";
}

$rs = mysqli_query($conn, $query) or die("Error : " . mysqli_error($conn));

我希望获得的结果是一个有效且具有正确语法的SQL查询。例如select * from Sheet1 where Doors>='$sprice' and Doors<='$eprice',如果访问者按价格过滤。

目前,我的代码是为了简单地向变量添加一个字符串。这意味着如果不按模型过滤,则会跳过模型,因为模型变量为空。问题是,如果按功耗过滤,SQL将变为select * from Sheet1 where Power>='$spower' and Power<='$epower' and。显然这不起作用,所以我需要帮助使代码确保它适用于每个过滤器组合。

2 个答案:

答案 0 :(得分:0)

我会这样做

$filters=array();

if(!empty($brand)){
          $branddata =implode("','",$brand);
          //testing removing query
          $filters[]= " Brand in('$branddata')";
      }

if(!empty($model)){
          $modeldata =implode("','",$model);
          //testing removing query
          $filters[]= " Model in('$modeldata') and"; 
      }


  if(!empty($spower) && !empty($epower)){
          $filters[]= " Power>='$spower' and Power<='$epower' and"; 
      }

  if(!empty($sprice) && !empty($eprice)){
          $filters[]= " Doors>='$sprice' and Doors<='$eprice'"; 
      }

$query = "select * from Sheet1 where";  

foreach ($filters as $filter) {
$query.=' AND '.$filter;

}

 $rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));

答案 1 :(得分:0)

在最后添加$query .= " 1 = 1";。我在你给定的代码中做了一些修改。看看。

<?php
$query = "SELECT * FROM `Sheet1` WHERE"; 

//filter query start 
if(!empty($brand)){
  $branddata = implode("','",$brand);
  $query  .= " (Brand in('$branddata')) AND";
}

if(!empty($model)){
  $modeldata = implode("','",$model);
  $query  .= " (Model in('$modeldata')) AND"; 
}

if(!empty($spower) && !empty($epower)){
  $query  .= " (Power>='$spower' AND Power<='$epower') AND"; 
}

if(!empty($sprice) && !empty($eprice)){
  $query  .= " (Doors>='$sprice' AND Doors<='$eprice') AND"; //Added 'AND'
}

$query .= " 1 = 1"; //Added new line

$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));
?>

在条件附加的每个查询上添加AND。然后,最后添加$query .= " 1 = 1";。这样可以免除你最后的额外AND。如果所有条件都不满足,那么您的查询将为SELECT * FROM Sheet1 WHERE 1 = 1。简单。并且,不要忘记区分查询条件。通过打开和关闭括号来区分您的条件。