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


当前回答

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

例子:

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

其他回答

当使用复选框作为数组时:

<input type="checkbox" name="food[]" value="Orange">
<input type="checkbox" name="food[]" value="Apple">

你应该使用in_array():

if(in_array('Orange', $_POST['food'])){
  echo 'Orange was checked!';
}

记得先检查数组是否被设置,例如:

if(isset($_POST['food']) && in_array(...

我已经把它固定成一个带有复选框的PHP表单

$categories = get_terms(['taxonomy' => 'product_cat', 'hide_empty' => false]); Foreach ($categories为$ categororie) { Echo "<input type="checkbox" value="$ categororie ->term_taxonomy_id" name="catselected[]"> $ categororie ->slug"; }

这样我把它添加到Woocommerce表。 wp_set_post_terms($product_id, $_POST['catselected'], 'product_cat');

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

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

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

一个极简的布尔检查开关位置保留

<?php

$checked = ($_POST['foo'] == ' checked');

?>

<input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>
<?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>