0

Looking for a way to change $$key to something like $$key_errorso the variable will look something like: $name_error outside the foreach loop.

Here is what I have so far:

  foreach ($_POST as $key => $value) {
    $$key = strip_tags(mysqli_real_escape_string($mysqli, $value));
     if (empty($value)) {
       // change variable below to something like $$key_error ($$name_error)
       $$key = 'is-invalid';

     } else {
       $$key = "value='$value'";
     }
  }

When an input is empty the user will return to the registration form, the input that is empty will have red bootstrap borders. When a field is not empty, the value will still be there so they do not have to do it all over.

<input type="text" name="name" class="form-control form-control-lg <?=$name?>" style="text-align:center;" placeholder="Voor- en achternaam" <?=$name?>>

I hope it all makes sense :)

3
  • 2
    Why? Anytime you use variable variables you should probably be using an array, which you already are using. Or build another $errors array. Commented Feb 27, 2018 at 19:38
  • Could you clarify that for me? Commented Feb 27, 2018 at 19:42
  • 1
    @Niels $errors[$key] = <error relative to that key here>; Commented Feb 27, 2018 at 19:50

1 Answer 1

1

Use arrays.

$errors = [];
$values = [];

foreach ($_POST as $key => $value) {
    // validation check for $value
    if (/*validation check fails*/) {
       $errors[$key] = 'error message specific to this field';
    } else {
        $values[$key] = htmlspecialchars($value);
    }
}

Then in your form, check for the array key matching your control name.

<input type="text" name="example"
    class="<?= isset($errors['example']) ? 'is-invalid' : '' ?> other classes"
    value="<?= $values['example'] ?? '' ?>">

You can also output the specific error message if you want to.

<div class="error"><?= $errors['example'] ?? '' ?></div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.