我的php脚本中有这个html表单
<form action="" method="post">
<div style="width: 30em;">
<label for="firstName">First name *</label>
<input type="text" name="firstName" id="firstName" value=""/>
<label for="lastName">Last name *</label>
<input type="text" name="lastName" id="lastName" value=""/>
<label for="password1">Choose a password *</label>
<input type="password" name="password1" id="password1" value=""/>
<label for="password2">Retype password *</label>
<input type="password" name="password2" id="password2" value=""/>
<label>Your gender: *</label>
<label for="genderMale">Male</label>
<input type="radio" name="gender1" id="genderMale" value="M" />
<label for="genderFemale">Female</label>
<input type="radio" name="gender" id="genderFemale" value="F" />
<label for="favoriteWidget">What's your favorite widget? *</label>
<select name="favoriteWidget" id="favoriteWidget" size="1">
<option value="superWidget">The SuperWidget</option>
<option value="megaWidget">The MegaWidget</option>
<option value="wonderWidget">The WonderWidget
</option>
</select>
<label for="newsletter">Do you want to receive our newsletter?</label>
<input type="checkbox" name="newsletter" id="newsletter" value="yes"/>
<label for="comments">Any comments?</label>
<textarea name="comments" id="comments" rows="4" cols="50"></textarea>
<div style="clear: both;">
<input type="submit" name="submitButton" id="submitButton" value="Send Details"/>
<input type="reset" name="resetButton" id="resetButton" value="Reset Form" style="margin-right: 20px;"/>
</div>
</div>
</form>
问题是当我提交表单并运行此php代码时:
if ( isset($_POST["submitButton"]) ) {
echo '<pre>' . print_r($_POST, true) . '</pre>';
}
我得到以下结果:
Array
(
[firstName] =>
[lastName] =>
[password1] =>
[password2] =>
[favoriteWidget] => superWidget
[comments] =>
[submitButton] => Send Details
)
最明显的是$ _POST数组中的性别和简报密钥丢失了吗? 这可能是什么原因?
答案 0 :(得分:3)
浏览器的所有复选框都是布尔值。 这不是关于PHP而是HTML。
要验证此人是否选择了简报字段,请尝试以下操作:
$_POST['newsletter'] = isset($_POST['newsletter']) ? $_POST['newsletter'] : 'no';
当未选中表单时,这会强制您的 $ _ POST 设置简报!
isset()验证您的变量是否存在,然后为此值设置默认值“否”。
您可以使用 array_key_exists()而不是isset()。
$_POST['newsletter'] = array_key_exists('newsletter', $_POST) ? $_POST['newsletter'] : 'no';