简体   繁体   中英

How to access a checkbox with a PHP script via POST when there are multiple checkboxes in the same form

I have a form for editing notifications that looks like:

<form action='edit.php' method = 'post'>
<b> Username</b>:<br/> <input type='text' name ='username' value ="<?=$username?>" /><br/>

<input type = "checkbox" id="r_notif" name="r_notif" checked="yes" /> Response Notifications<br/>
<input type = "checkbox" id="c_notif" name="c_notif" checked="yes" /> Comment Notifications<br/>
<input type ='submit' value = 'SEND' /> 
</form>

In edit.php , I want to set the value of $r_notif to 1 if checked ="yes" for the input with name resp_notif . Similarly, I want to set the value of $c_notif to 1 if checked = "yes" for input c_notif . I set them to zero otherwise in each case.

Problem is I only know how to access $_POST['name_of_field'] and don't know how to access the checked value...How can this be done (in PHP or otherwise)

Thanks!

if(isset($_POST['name_of_field']))

Try

var_dump($_POST['r_notif']);
var_dump($_POST['c_notif']);

and different variations of checking/not checking your checkboxes. You should be able to answer your own question (literally, this is much encouraged on stackoverflow!) pretty soon.

It's a good idea to add value fields to your markup, that way you can be sure of what the contents of the POST will be, and it will not vary between browsers;

<input type = "checkbox" id="r_notif" name="r_notif" checked="yes" value="yes" />
<input type = "checkbox" id="c_notif" name="r_notif" checked="yes" value="yes" />

Then in your php;

if($_POST['r_notif'] == 'yes') $r_notif = 1;
else $r_notif = 0;
if($_POST['c_notif'] == 'yes') $c_notif = 1;
else $c_notif = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM