如果在Mysql中声明选择查询umer

时间:2013-11-26 08:08:55

标签: php mysql

我想用帖子过滤mysql查询。如果我在post中得到一个特殊值然后过滤它,如果它在post中得到值'ALL',那么显示所有值都不过滤。我试过这样的。它工作,但我想在一个查询中处理它。

           if($_POST['comp']== 'all' && $_POST['cat']== 'all'){
      return  $this->db->select("SELECT * FROM items order by name");
    }
    if($_POST['comp']!= 'all' && $_POST['cat']!= 'all'){
      return  $this->db->select("SELECT * FROM items where company = '$_POST[comp]' and             category = '$_POST[cat]' order by name");
    } 
    if($_POST['comp']!= 'all'){
      return  $this->db->select("SELECT * FROM items where company = '$_POST[comp]' order by name");
    }
    if($_POST['cat']!= 'all'){
      return  $this->db->select("SELECT * FROM items where category = '$_POST[cat]' order by name");
    }

3 个答案:

答案 0 :(得分:2)

    prepare the query like this:
        $query .= "SELECT * FROM items where 1=1"; 
        if($_POST['comp']!= 'all')
        {
          $query .= " and company = '$_POST[comp]'";            
        }
        if($_POST['cat']!= 'all')
        {
          $query .= " and category = '$_POST[cat]'";
        }
         $query .= " order by name";

return  $this->db->select($query);

答案 1 :(得分:0)

创建一个变量(数组)来存储过滤规则,然后检查它的长度,内爆并附加到查询字符串

前:

$posted = $_POST;
$where = array(1);//no need to check length if you initialise with this array
foreach($posted as $k=>$v){
    if($k != 'ALL')$where[] = ... //add new filter from $post
    else {
        $where = array(1);
        break;//break this loop when see 'ALL' option
    }
}
$where = implode(' and ',$where); //append this to query string

答案 2 :(得分:0)

如果您只想执行一个查询,只需将其更改为if / else语句:

if($_POST['comp']== 'all' && $_POST['cat']== 'all'){
    return  $this->db->select("SELECT * FROM items order by name");
}else if($_POST['comp']!= 'all' && $_POST['cat']!= 'all'){
    return  $this->db->select("SELECT * FROM items where company = '$_POST[comp]' and category = '$_POST[cat]' order by name");
}else if($_POST['comp']!= 'all'){
    return  $this->db->select("SELECT * FROM items where company = '$_POST[comp]' order by name");
}else if($_POST['cat']!= 'all'){
    return  $this->db->select("SELECT * FROM items where category = '$_POST[cat]' order by name");
}

现在只执行1个SQL查询,而不是所有与过滤器匹配的查询。