What are some common methods to retain form data in PHP after submitting and displaying error messages?
When submitting a form in PHP and displaying error messages, it is important to retain the form data that the user entered so they do not have to re-enter everything. One common method to achieve this is by using the $_POST superglobal array to populate the form fields with the previously submitted data.
<?php
// Initialize variables to store form data
$name = '';
$email = '';
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$name = $_POST['name'];
$email = $_POST['email'];
// Validate form data
if (empty($name)) {
$error = "Name is required";
}
if (empty($email)) {
$error = "Email is required";
}
}
?>
<form method="post">
<input type="text" name="name" value="<?php echo $name; ?>" placeholder="Name">
<input type="email" name="email" value="<?php echo $email; ?>" placeholder="Email">
<button type="submit">Submit</button>
</form>
<?php
// Display error messages
if (isset($error)) {
echo $error;
}
?>