PHP Complete Form Example
This section will introduce how to ensure that all fields are correctly filled before the user submits data by clicking the "Submit" button.
PHP - Ensuring Input Values in the Form
After the user clicks the submit button, to ensure the correctness of the field values, we insert PHP scripts into the HTML input elements, with field names: name, email, and website. In the textarea field for comments, we place the script between the <textarea>
and </textarea>
tags.
The PHP script outputs values for the variables: $name, $email, $website, and $comment.
We also need to check the selected radio button. For this, we must set the checked attribute (not the value attribute of the radio button):
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
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
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
PHP - Complete Form Example
Below is the complete PHP form validation example code:
Example
The execution result of the example is similar to the following: