用 PHP/sql 编写一个小过滤器。用户从两个过滤器选项中进行选择,但是他们也可以选择在过滤器中选择“全部”,基本上只是使查询不过滤该结果。
使用基本的 WHERE 方法,查询看起来像这样
$query = ("SELECT * FROM user WHERE userid = '$userid' AND department = '$department'");
我将如何调整它以使过滤器返回该特定过滤器的所有结果?因为在 php 中编写一堆 if else 语句似乎很笨重。
$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");