How can form data be retained and displayed after submission in PHP?
To retain and display form data after submission in PHP, you can store the form data in variables and then use those variables to pre-fill the form fields upon submission. This can be done by checking if the form has been submitted and if so, retrieving the form data from the POST array and assigning it to the variables. Then, in the form fields, you can use PHP echo statements to display the stored form data.
<?php
// Initialize variables to store form data
$name = '';
$email = '';
// Check if form has been submitted
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Retrieve form data from POST array
$name = $_POST['name'];
$email = $_POST['email'];
}
// Display the form with stored data
echo '<form method="post">';
echo 'Name: <input type="text" name="name" value="' . $name . '"><br>';
echo 'Email: <input type="email" name="email" value="' . $email . '"><br>';
echo '<input type="submit" value="Submit">';
echo '</form>';
?>
Keywords
Related Questions
- What best practice should be followed when writing data to a file in PHP to ensure all data is captured and not just the last entry?
- What are the potential benefits of using a fixed image template with variable data insertion instead of dynamically generating images in PHP?
- What are some common reasons for a PHP file being interpreted as HTML instead?