Html表单提交复选框 - 在mysql表中更改值[关闭]

Html表单提交复选框 - 在mysql表中更改值[关闭]

问题描述:

i have a database which is composed by some field that are booleans, so in my html form i made the input type set to check box and i want to make if checked = "True", uncheck = "false".
How can i archive that ? By now if i check them i see a 0, if i don't check i don't see nothing. I have tried to put and hidden field and work with that but not getting any results.

If you need code or print screen to understand the question better please tell me. Thank you.

我有一个数据库,由一些字段组成的布尔值,所以在我的html表单中我做了输入类型 设置为复选框,我想制作if checked =“True”, uncheck =“false”。
如何归档? 到现在如果我检查它们我看到0,如果我不检查我什么也看不到。 我试图放置并隐藏字段并使用它但没有得到任何结果。 p>

如果您需要代码或打印屏幕来更好地理解问题,请告诉我。 谢谢。 p> div>

That's the default behavior of checkbox inputs:

  • Post the value of the parameter "value" if the checkbox is checked
  • Post nothing if the checkbox isn't checked

so, if you have something like:

<input type="checkbox" value="TRUE" name="my_checkbox" />

In PHP, you could do something like:

if (isset($_POST["my_checkbox"])) {
    echo "checkbox is checked";    
} else {  
    echo "checkbox not checked";
}

If you want absolutely to post something even if the checkbox isn't checked, as you said, you ca use an hidden field like this:

<input type="checkbox" value="TRUE" name="my_checkbox_1" />
<input type="hidden" value="my_checkbox_1,my_checkbox_2,my_checkbox_3" name="my_checkboxes" />

the hidden field "my_checkboxes" would hold all the name of all the check boxes in your form.

Then, you can take the value of $_POST["my_checkboxes"], split the value of it (with ","), and loop through all the checkboxes:

$checkboxes = explode(",", $_POST['my_checkboxes']);
foreach($checkboxes as $checkbox) {
  $checkbox_value = $_POST[$checkbox];
  if (isset($checkbox_value)) {
    echo "checkbox " . $checkbox . " was checked";
  } else {
   echo "checkbox " . $checkbox . "wasn't check";
  }
}

That solution would be good if you have a dynamic form with an unknown number of checkboxes.

Posting something as "my_checkbox" ($_POST['my_checkbox']) if it is checked or not with different value would be possible with JavaScript (but I don't recommend it).

HTML Checkboxes return a value if they are checked, OR return nothing if not checked. So use isset()

HTML:

<input type="checkbox" value="1" name="chk1" />Label 1
<input type="checkbox" value="1" name="chk2" />Label 2

PHP

$chk1 = (isset($_POST['chk1']))? true : false;
$chk2 = (isset($_POST['chk2']))? true : false;