how do I get all checkbox variables even if not checked from HTML to PHP?

倾然丶 夕夏残阳落幕 提交于 2019-11-27 11:49:26

I just ran into this problem myself. I solved it by adding a duplicate hidden field with the same name. When the browser sends this information, the second field overrides the first (so ensure that the hidden field comes first).

<input type="hidden" name="foo" value="">
<input type="checkbox" name="foo" value="bar">

If the checkbox is not checked you get:

$_REQUEST[ 'foo' ] == ""

If the checkbox is checked you get:

$_REQUEST[ 'foo' ] == "bar"

This isn't something that can be done purely in PHP.

Browsers only send information about checkboxes if they are checked, if you want to also send information about unchecked checkboxes, you'll have to add hidden fields in the form and use javascript to manage them.

I just stumbled across this problem myself and I sorted it by updating all values in the database to unchecked then re-checking only the ones that are in the POST data, this works fine for me but might not be everyone's cup of tea.

A pure PHP implementation doesn't seem possible, you can try using jQuery/AJAX though.

GmonC

Suppose you have a 3 checkboxes you want to check, and update_settings is the name of your functions that take the checkbox name as a first argument and a bool value as a second one (activate or not).

Take the following snippet:

$checkboxes = array("checkbox1", "checkbox2", "checkbox3");
foreach($checkboxes as $checkbox){
    $checked = isset($_POST[$checkbox]);
    update_settings($checkbox, $checked);
}

Althouth Peter Kovacs solution it's going to work, I don't think it's practical since you can already check your variables using isset.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!