What is the best way to supply many arguments to a

2019-08-30 18:24发布

问题:

I have created a form with several user inputs but have the tedious task of checking whether each individual input is not empty before submission. Is there a quicker way, (such as using arrays perhaps) of listing all arguments to the if statement?

At the moment my code looks like this but if possible I would like it to be more efficient in future, like if I were to add more inputs.

<form action="sign-up.php" method="post" autocomplete="off" >
Name:<input type="text" name="name" />
Username:<<input type="text" name="username"  /><br />
Password:<input type="password" name="password1" /><br />
Re-type Password:<input type="password" name="password2"  /><br />
Email:<input type="text" name="email"  />
Address:<input type="text" name="address"  />
Post Code:<input type="text" name="postcode"  />
City:<input type="text" name="city"  />
<input class="submit" type="submit" value="sign up" />
</form>

<?php
if (!empty($_POST['name']) 
&& !empty($_POST['username']) 
&& !empty($_POST['password1']) 
&& !empty($_POST['password2']) 
&& !empty($_POST['email'])   
&& !empty($_POST['address'])
&& !empty($_POST['postcode']) 
&& !empty($_POST['city']) )
{
echo "information has been submitted";
}
else {
echo "please fill in all fields!"
}

?>

If you have any suggestions please comment.

回答1:

So what this will do is loop through the $_POST values and check if they're empty. If one is found to be empty, it will set $hasErrorOccurred to true. The if statement below will determine if the input check is successful or not.

    $hasErrorOccurred = false;

    foreach ($_POST as $key => $value) {
        if (empty($_POST[$key])) {
            $hasErrorOccurred = true;

            break;
        }
    }

    if ($hasErrorOccurred) {
        // Your error code here.
    } else {
        // Your successful code here.
    }

Reading material:

break;



回答2:

If you want to assign variables to each field input, this is how I did it.

foreach ($_POST as $key => $value) {

 $$key = $_POST[$key];  //assigns input name to variable with the same name.

    }

if(!empty($$key)) {

//code if all fields are not empty  

}
else {

    echo "Please fill in all fields";

}


回答3:

Here is the way I tried to describe on comments to Script47's answer so I can clarify my point a little bit better:

$requiredFields = ['name','username','password1','password2'];
foreach ($requiredFields as $field) {
    if (!array_key_exists($field, $_POST) || empty($_POST[$field])) {
        displayMissingFieldAlert($field);
    }
}
// do the submit etc.
...

This way you can catch if a field is somehow forgotten, misspelled or left out of the submission.