如何阅读,如果一个复选框被选中在PHP?


当前回答

<form>
<input type="check" id=chk1 value="1">
<input type="check" id=chk2 value="1">
<input type="check" id=chk3 value="1">
</form>

当你检查chk2时,你可以看到如下值:

<?php
foreach($_POST as $key=>$value)
{
    if(isset($key))
        $$key=strip_tags($value);
}
insert into table (chk1,chk2,chk3) values ('','1','');
?>

其他回答

你可以用简短的if来表达:

$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;

或者使用新的PHP7空合并运算符

$check_value = $_POST['my_checkbox_name'] ?? 0;

Zend框架在复选框上使用了一个不错的hack,你也可以自己做:

生成的每个复选框都与一个同名的隐藏字段相关联,位于复选框之前,值为“0”。然后,如果您的复选框为值“1”,则在结果get或POST中始终获得“0”或“1”值

<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1"> 

在BS3中

  <?php
                  $checked="hola";
                  $exenta = $datosOrdenCompra[0]['exenta'];
                  var_dump($datosOrdenCompra[0]['exenta']);
                  if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){

                      $checked="on";

                  }else{
                    $checked="off";
                  }

              ?>
              <input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>

请注意isset($datosOrdenCompra[0]['exenta'])的用法

$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;

根据表单的操作,您可以在$_POST或$_GET数组中检查相应的值是否已设置且非空。

例如:使用一个名为"test"的POST表单(即:<input type="checkbox" name="test">,你会使用:

if(isset($_POST['test']) {
   // The checkbox was enabled...

}