I am trying to create a form where if a user doesn't enter information into a specific input then on submission of the form, the user is alerted to fill in that input field only (e.g. "Please enter a username").
Currently I have a foreach loop that loops through each input field of the form and assigns a variable with the same name as the field (i.e. $name = $_POST['name']).
What would I implement in my code so I could check each individual input field is empty or not and tell the user this, but keep the code to a bare minimal?
foreach ($_POST as $key => $value) {
$$key = $_POST[$key]; //assigns variable to input.
}
if(!empty($$key)) {
//code if all fields are not empty
}
else {
echo "Please fill in all fields";
}
While I do not agree with how you are doing this, a solution would be to add an error array
to your first foreach
loop.
foreach ($_POST as $key => $value) {
${$key} = $_POST[$key];
// If the field is empty, set an error
if( empty($value) ) {
$errors[] = 'Please enter a ' . $key . '.';
}
}
And then change the bottom to check for the error array
. If it's empty, run your code to complete the form submission. If not, loop through the errors.
if( empty($errors) ) {
//code if all fields are not empty
}
else {
// Loop through each error found
foreach($errors as $error) {
echo $error;
}
}