我在PHP中运行此SQL查询:
$stmt = $pdo_conn->prepare("SELECT * from porting order by field(status, 'Submitted', 'Rejected', 'Cancelled', 'Accepted') ");
$stmt->execute(array());
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
但我希望能够添加复选框来修改查询而不刷新页面
例如,
<input type="checkbox" name="status" value="Submitted" />
<input type="checkbox" name="status" value="Rejected" />
<input type="checkbox" name="status" value="Cancelled" />
<input type="checkbox" name="status" value="Accepted" />
因此,如果选中值为“已提交”的输入,则查询将更改为:
SELECT * from porting where status = 'Submitted'
如果同时选中值为“已提交”和“已接受”的输入,则查询将为:
SELECT * from porting where status = 'Submitted' or status = 'Accepted'
答案 0 :(得分:2)
您的复选框应使用数组语法
<input type="checkbox" name="status[]" value="Submitted" />
<input type="checkbox" name="status[]" value="Rejected" />
<input type="checkbox" name="status[]" value="Cancelled" />
<input type="checkbox" name="status[]" value="Accepted" />
从那里,你implode。
$sql = "SELECT * from porting where status IN('".implode("', '", $_POST['status'])."')";
警告:上面的SQL查询对SQL INJECTION 是健全的,但它应该让您走上正轨。
答案 1 :(得分:0)
$checkboxes = $_POST['status'];
if(count($checkboxes)) {
$where_clause = ' where';
}
else {
$where_clause = '';
}
foreach($checkboxes as $el) { $el = addslashes($el);
$where_clause .= " status = '$el' or";
}
$where_clause = substr($where_clause, 0, -2);
$query = 'select * from porting' . $where_clause;
最后,$query
将包含如下字符串:
select * from porting where status = 'Submitted' or status = 'Cancelled'
如果您想发送多个值,则应使用name="status[]"
代替name="status"
。