PHP 将复选框的值传递给查询

PHP pass value of checkbox to query

您好,我有这个带有 3 个复选框的表单:

<form action="send.php">
<input type="checkbox" name="txt_group" value="CID">CID
<input type="checkbox" name="txt_group" value="OSDS">OSDS  
<input type="checkbox" name="txt_group" value="SGO">SGO
<input type="submit">
</form>

在我的 send.php 中我有这个代码:

$stmt = $dbc->query("SELECT * FROM tblcontactlist WHERE contactGroup=:cgroup");
$stmt->bindParam(':cgroup', $_POST['txt_group']);
$stmt->execute();

我认为如果我只选中 1 个复选框,这会起作用。但是如果我 select 2-3 复选框呢?此查询仍然有效吗?

将输入名称更改为数组

<input type="checkbox" name="txt_group[]" value="CID">CID

然后 $_POST['txt_group'] 获取您检查过的数组列表

在您的代码中,您为所有复选框指定了相同的名称,如下所示

<input type="checkbox" name="txt_group" value="CID">CID

尝试将名称更改为数组,如

<input type="checkbox" name="txt_group[]" value="CID">CID
<input type="checkbox" name="txt_group[]" value="OSDS">OSDS  
<input type="checkbox" name="txt_group[]" value="SGO">SGO

并使用

在服务器端打印
print_r($_POST['txt_group']);

如果不是 array,多个 input 不能有相同的 name,否则它们将被 last 覆盖。尝试 -

<form action="send.php">
<input type="checkbox" name="txt_group[]" value="CID">CID
<input type="checkbox" name="txt_group[]" value="OSDS">OSDS  
<input type="checkbox" name="txt_group[]" value="SGO">SGO
<input type="submit">
</form>

使用 php 示例查询将是 -

$values = implode("','", $_POST['txt_group']);
$values = $mysqli->real_escape_string($values);
"SELECT * FROM tblcontactlist WHERE contactGroup IN ('" . values . "')"

是的,如果您要将 post 值作为数组,变量名称的方括号是必需的。这个名称="text_group[]" 是正确的..