我尝试做一些条件,当我设置文本字段而不是单选按钮时,我将得到一个PHP错误。 ................................................... ................................................... ......................................
这是我的代码:
<form method="post">
<input type="text" name="name">
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<input type="submit">
</form>
<?php
$name = $nameErr = $gender = $genderErr = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST['name'] == '' || $_POST['gender'] == '') {
echo('all filed');
}
else {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = $_POST["name"];
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = $_POST["gender"];
}
}
}
echo $name. ' ' .$gender;
?>
答案 0 :(得分:2)
尝试:
if ((isset($_POST['name']) && $_POST['name']) == '' || (isset($_POST['gender']) && $_POST['gender'] == '')) {
echo('all filed');
}
如果未设置$_POST['gender']
,则必须放置条件。
您可以使用:
echo "<pre>";
print_r($_POST);
exit;
答案 1 :(得分:0)
根据您的代码,请使用以下条件
if (isset($_POST["name"]) && $_POST["name"] != "") {
$name = $_POST["name"];
} else {
$nameErr = "Name is required";
}
if (isset($_POST["gender"]) && $_POST["gender"] != "") {
$gender = $_POST["gender"];
} else {
$genderErr = "Gender is required";
}
答案 2 :(得分:0)
在检查“名称”和“性别”字段时,情况不正确。您在条件中指定了“ OR(||)”,因此这意味着任何字段为空,它将返回true。您的情况如下:
if ($_POST['name'] == '' || $_POST['gender'] == '') {
echo('all filed');
}
将其更改为:
if ($_POST['name'] == '' && $_POST['gender'] == '') {
echo('all filed');
}
希望您的问题能得到解决。
答案 3 :(得分:0)
尝试下面的代码,问题是您试图在条件之外打印值。
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['name']) || empty($_POST['gender'])) {
echo('all filed');
}
else {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
}
else {
$name = $_POST["name"];
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
}
else {
$gender = $_POST["gender"];
}
echo $name . ' ' . $gender;
}
}
答案 4 :(得分:-1)
更改此内容:
<form method="post">
<input type="text" name="name">
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<input type="submit">
</form>
对此:
<form method="post">
<input type="text" name="name">
<input type="radio" name="gender" value="female" checked>Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<input type="submit">
</form>