How can the values of form fields be retained in PHP when displaying the form again after an error?
To retain the values of form fields in PHP when displaying the form again after an error, you can store the submitted values in session variables and populate the form fields with these values. This ensures that the user doesn't have to re-enter all the data if there was an error in the form submission.
<?php
session_start();
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Store form values in session variables
$_SESSION['name'] = $_POST['name'];
$_SESSION['email'] = $_POST['email'];
// Add validation and processing logic here
// If there is an error, redirect back to the form
header("Location: form.php");
exit;
}
// Populate form fields with session values
$name = isset($_SESSION['name']) ? $_SESSION['name'] : '';
$email = isset($_SESSION['email']) ? $_SESSION['email'] : '';
?>
<form method="post" action="form.php">
<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>