if (isset($_POST['register'])) {
$email = $_POST['email'];
$username = $_POST['username'];
$pass = $_POST['password'];
$rep_pass = $_POST['rep-password'];
$firstname = $_POST['firstname'];
$surname = $_POST['surename'];
$phonenr = $_POST['phone-nr'];
$place = $_POST['place'];
}
if ($email != "" && $username != "" && $pass != "" && $rep_pass != "" && $firstname != "" && $surname != "" && $phonenr != "" && $place != "") {
}
在第二个if
语句的条件下,是否有更短的方式与我正在做的相同?
答案 0 :(得分:4)
$required = ['email', 'username', 'password', ...];
foreach($required as $field)
if(empty($_POST[$field]))
throw new EpicFailureException("Mandatory field '$field' is empty");
答案 1 :(得分:0)
您可以使用预设接受的postvars事物。 您可以在验证期间添加自定义错误消息等,并且我的代码会自动实例化您的变量。唯一的问题是我没有考虑破折号,但您可以考虑从表单名称中删除它们。
$accepted = array('register','email','username','password','rep-password','firstname','surename','phone-nr','place');
$_POST = array('register'=>'blah','email'=>'blah','username'=>'blah','password'=>'blah','rep-password'=>'blah','firstname'=>'blah','surename'=>'blah','phone-nr'=>'blah','place'=>'blah');
$proper = true;
$erroron = "";
foreach($accepted as $val) {
if(isset($_POST[$val])) {
trim($_POST[$val]);
if(!empty($_POST[$val])) {
$$val = $_POST[$val];
}
else {
$proper=false;
$erroron = "Error occured on $val which is empty";
break;
}
}
else {
$proper = false;
$erroron = "Error occured on $val which is not defined";
break;
}
}
if($proper) {
echo "email = $email, you might want to consider removing dashes from form names to auto instantiate those variables";
}
else {
echo "Not everything was done properly. The error message is: $erroron";
}
答案 2 :(得分:0)
您可以将值放入数组中,然后使用内置函数array_filter()
。
如果您没有向array_filter()
提供回调函数,它只会删除数组的false或空值。
然后计算修改前后的值,如果它们是!=缺少值。
if (isset($_POST['register'])) {
$user['email'] = $_POST['email'];
$user['username'] = $_POST['username'];
$user['pass'] = $_POST['password'];
$user['rep_pass'] = $_POST['rep-password'];
$user['firstname'] = $_POST['firstname'];
$user['surname'] = $_POST['surename'];
$user['phonenr'] = $_POST['phone-nr'];
$user['place'] = $_POST['place'];
}
$nbArg = count($user);
if($nbArg != count(array_filter($user))) {
echo "One Value is missing"
}