我有6个<select>
个方框。我正在根据<select>
框创建报告。我所做的是创建一个表单并设置GET方法,然后通过下一页的$ _GET方法获取这些值。像
<form method="get" action="report.php">
<select name="select1">
<option value="none">Select value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="select2">
<option value="none">Select value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="select3">
<option value="none">Select value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
.....................
</form>
这是PHP代码。 (这些都是样本数据:P)只是想告诉别人我的问题。我正在检查所有值,如果它的值等于none,则执行此操作,等等。
if(
$cby == "none"
&& $crequirment == "none"
&& $cdepartment == "none"
&& $period == "none"
&& $ccontact == "none"
&& $cattend == "none"
)
{
$query = mysqli_query($db, "SELECT * FROM customer");
}
else if (
$cby != "none"
&& $crequirment == "none"
&& $cdepartment == "none"
&& $period == "none"
&& $ccontact == "none"
&& $cattend == "none"
)
{
$query = mysqli_query($db, "SELECT * FROM customer WHERE cby = $cby");
}
else if (
$cby == "none"
&& $crequirment == "none"
&& $cdepartment != "none"
&& $period == "none"
&& $ccontact == "none"
&& $cattend == "none")
{
$query = mysqli_query($db, "SELECT * FROM customer WHERE cdepartment = $cdepartment");
}
else if..........
我想要的是尽可能简单。我应该采用什么方法呢?
答案 0 :(得分:1)
优化您的代码。
创建名称为data[cby]
,data[crequirment]
的选择。
而不是none
使用空字符串。
在PHP中:
if (isset($_GET['data']) {
$where = [];
foreach ($_GET['data'] as $name => $value) {
if ($value != '') {
$where[] = $name."=".$value; // sanitize `$name` and `$value` first
}
}
if (!empty($where)) {
$whereString = ' WHERE '.implode(' AND ', $where);
} else {
$whereString = '';
}
$query = mysqli_query($db, "SELECT * FROM customer".$whereString);
}