PHP Form Validation - Complete Form Example

This section demonstrates how to preserve the values in the input fields after the user submits the form.

PHP - Preserve the values in the form

If you need to display values in the input fields after the user clicks the submit button, we have added a small PHP script in the value attribute of the following input fields: name, email, and website. In the comment text box field, we placed the script between <textarea> and </textarea>. These scripts output the values of the $name, $email, $website, and $comment variables.

Then, we also need to display which radio button is selected. For this, we must manipulate the checked attribute (not the value attribute of the radio button):

Name: <input type="text" name="name" value="<?php echo $name;?>">
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
Website: <input type="text" name="website" value="<?php echo $website;?>">
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male

PHP - Complete Form Example

Below is the complete code for the PHP form validation example:

Example

Run Instance