What are best practices for handling form data in PHP to prevent issues like only the last entry being displayed in a table?

When handling form data in PHP, the issue of only the last entry being displayed in a table can be resolved by storing each form submission in an array or a database before displaying them. This way, all entries will be retained and displayed properly in the table.

<?php
// Initialize an empty array to store form submissions
$form_submissions = [];

// Check if form data has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data and store it in an array
    $form_data = [
        'name' => $_POST['name'],
        'email' => $_POST['email'],
        'message' => $_POST['message']
    ];
    
    // Add the form data to the submissions array
    $form_submissions[] = $form_data;
}

// Display all form submissions in a table
echo "<table>";
foreach ($form_submissions as $submission) {
    echo "<tr>";
    echo "<td>" . $submission['name'] . "</td>";
    echo "<td>" . $submission['email'] . "</td>";
    echo "<td>" . $submission['message'] . "</td>";
    echo "</tr>";
}
echo "</table>";
?>