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.
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. Theif statement
below will determine if the input check is successful or not.Reading material:
break;
If you want to assign variables to each field input, this is how I did it.
Here is the way I tried to describe on comments to Script47's answer so I can clarify my point a little bit better:
This way you can catch if a field is somehow forgotten, misspelled or left out of the submission.