SQL查询where filter = *

时间:2013-05-27 06:53:16

标签: php sql filter where

在PHP / sql中编写一个小过滤器。 用户从两个过滤器选项中进行选择,但是他们也可以选择在过滤器中选择“全部”,基本上只是使查询不过滤该结果。

使用基本的WHERE方法,查询如下所示

$query = ("SELECT * FROM user WHERE userid = '$userid' AND department = '$department'");

我如何调整此选项以使过滤器返回该特定过滤器的所有结果?在php中写一堆if else语句似乎很笨重。

1 个答案:

答案 0 :(得分:1)

$expected_filters = array(
  // 'mysql_column'=>'php_variable',
  'userid'=>'userid',
  'department'=>'department',
);


$final_filters = array();

foreach ($expected_filters as $k => $v) {
  if (isset($_POST[$v]) && trim($_POST[$v])) {
    $final_filters[] = sprintf("%s= '%s'", $k, $v);      
  }    
}

$where = '';

if (count($final_filters)>0) {
    $where = implode(' AND ', $filter);
    $where = ' WHERE ' . $where;
}

$query = ("SELECT * FROM user $where");