Home > Software design >  Keep data from inputs after failed validation in PHP
Keep data from inputs after failed validation in PHP

Time:11-17

Here's the situation: registration.php with inputs (like firstname, lastname, password) and registrationErrors.php - having self-written error-checks and returning the type of error to the initial registration.php, where it is shown to the user.

In case one of my self-written error occurs, I'd like to save the inputs (registration.php) the user has already done and only clear the input with the error in it.

I have seen a couple of posts having the same problem - but mine's slightly different. Since the data is sent to

<form action="registrationErrors.php" method="post" ...>

, the suggestion

value="<?php echo isset($_POST["firstname"]) ? $_POST["firstname"] : ''; ?>"

doesn't work, since it would have to be sent to:

<form action="registration.php"...>

Any idea how to keep my structure of the two php-files and still have the already-input data saved?

CodePudding user response:

You can save data on session in a file registrationErrors.php and then retrieve it on registration.php. Also You can send data using GET parameter to registration.php.

value="<?php echo isset($_SESSION["firstname"]) ? $_SESSION["firstname"] : ''; ?>"

this will work.

OR even

value="<?php echo isset($_GET["firstname"]) ? $_GET["firstname"] : ''; ?>"

this will work

CodePudding user response:

Please use session variables to do what you want

PHP (submission form)

<?php session_start(); ?>

<!-- other statements -->

<form action="registrationErrors.php" method="post" ...>
<!-- other inputs -->
<input name=firstname value="<?= $_SESSION['firstname']  ?? '' ?>"
<input type=submit>
</form>

registrationErrors.php

<?php session_start();

$_SESSION["firstname"]=$_POST["firstname"]) ?? '';

// the above is equivalent to:
// $_SESSION["firstname"] = isset($_POST['firstname']) ? $_POST['firstname'] : '';

// other statements , error checking, etc

?>

  • make sure you have put session_start(); at the start of all related php scripts
  • please do the same for lastname, etc.
  • Related