user3208001
user3208001

Reputation: 1

How do I keep data in forms during PHP error validation?

I have a user registration page that I am working on. Once form is submitted using the "Register" button, then it uses POST to send it to the same page, which then processes the entered data, and searches to see if it meets the requirements using an IF statement.

Here's an example:

    if (strlen($password) < 7)
    echo ("<span class=error>Password must be at least 8 characters long.<br></span>"); 

I have it set up where if any of the error IF statements are met, that the form stops processing and displays an error. My issue is that once the form is reloaded like that, the data disappears from the form.

I have tried using code like this to keep the data in the form:

<td>First Name: </td>
          <td width="55%"><input type='text' name='firstname' placeholder="First Name" value="<?PHP $_GET['firstname'] ?>" width="300px">
            *</td>

However, setting the value as the POST information does not seem to work. What is the best method to keep data in the form?

Upvotes: 0

Views: 1340

Answers (1)

SBD
SBD

Reputation: 446

I haven't tested this, but I think this should work.

In your code you forgot to echo the posted variable.

Assumed the form has been posted with errors you can do it like this:

<?php $firstname = htmlspecialchars($_POST['firstname']); ?>
<td>First Name: </td>
              <td width="55%"><input type='text' name='firstname' placeholder="First Name" value="<?php if (isset($firstname)) { echo $firstname; }" width="300px">
                *</td>

Upvotes: 1

Related Questions