What is the best practice for initializing form values in PHP after submission?
When a form is submitted in PHP, it is important to initialize the form values with the submitted data so that the user does not lose their input if there are validation errors. One way to achieve this is by checking if the form has been submitted using the `$_POST` superglobal and then setting the form values to the submitted data. This ensures that the form fields are pre-filled with the user's input when the form is redisplayed.
<?php
// Initialize form values
$name = '';
$email = '';
// Check if form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Set form values to submitted data
$name = $_POST['name'];
$email = $_POST['email'];
}
// Display form with pre-filled values
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<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>