如何使用PHP脚本通过POST访问一个复选框,当有多个复选框在同一表单


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

我有一个用于编辑通知的表单,它看起来像:

<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>

edit.php中,如果名称为resp_notif的输入为checked ="yes",我想将$r_notif的值设置为1。同样,如果输入c_notifchecked = "yes",我想将$c_notif的值设置为1。我在每种情况下都将它们设置为零。

问题是我只知道如何访问$_POST['name_of_field'],不知道如何访问检查值…如何做到这一点(在PHP或其他)

谢谢!

在标记中添加值字段是个好主意,这样就可以确定POST的内容是什么,并且不会因浏览器而异;

<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" />

然后在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;
if(isset($_POST['name_of_field']))

Try

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

和选择/不选择复选框的不同变体。你应该很快就能回答你自己的问题了(从字面上看,这在stackoverflow上是非常鼓励的!)