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


当前回答

$is_checked = isset($_POST['your_checkbox_name']) &&
              $_POST['your_checkbox_name'] == 'on';

短路计算将会注意,这样您就不会在your_checkbox_name未提交时访问它。

其他回答

让你的html复选框将是这样的

<input type="checkbox" name="check1">

提交表单后,你需要检查

if (isset($_POST['check1'])) {

    // Checkbox is selected
} else {

   // Alternate code
}

假设check1应该是复选框的名称。如果你的表单提交方法是GET,那么你需要检查$_GET变量像

if (isset($_GET['check1'])) {

   // Checkbox is selected
} 
<?php

  if (isset($_POST['add'])) {

    $nama      = $_POST['name'];
    $subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";

    echo "Name: {$nama} <br />";
    echo "Subscribe: {$subscribe}";

    echo "<hr />";   

  }

?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >

  <input type="text" name="name" /> <br />
  <input type="checkbox" name="subscribe" value="news" /> News <br />

  <input type="submit" name="add" value="Save" />

</form>
<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','');
?>

要检查是否选中复选框,请使用empty()

当表单提交时,复选框将总是被设置,因为所有POST变量将与表单一起发送。

检查复选框是否选中为空,如下所示:

//Check if checkbox is checked    
if(!empty($_POST['checkbox'])){
 #Checkbox selected code
} else {
 #Checkbox not selected code
}

了解isset,它是一个内置的“函数”,可以在if语句中使用,以判断一个变量是否已被使用或设置

例子:

    if(isset($_POST["testvariabel"]))
     {
       echo "testvariabel has been set!";
     }