How can one avoid overwriting data in a session variable when multiple form submissions are involved?

To avoid overwriting data in a session variable when multiple form submissions are involved, you can append new data to the existing session variable rather than overwriting it each time a form is submitted. This can be achieved by storing the data in an array within the session variable and updating the array with new form submissions.

session_start();

// Initialize session variable as an empty array if it doesn't exist
if (!isset($_SESSION['formData'])) {
    $_SESSION['formData'] = [];
}

// Append new form data to the session variable array
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $newFormData = $_POST['data']; // Assuming 'data' is the form field name
    $_SESSION['formData'][] = $newFormData;
}