How can sessions be effectively used to pass IDs in PHP forms within a While loop?

When passing IDs in PHP forms within a While loop, sessions can be effectively used to store and retrieve the ID values. By storing the ID in a session variable, it can be accessed across multiple pages without the need to pass it through form submissions repeatedly. This approach simplifies the code and ensures that the correct ID is maintained throughout the user's session.

<?php
session_start();

// Assume $result contains the data fetched from a database query
while ($row = mysqli_fetch_assoc($result)) {
    $_SESSION['id'] = $row['id'];

    // Display form with ID value
    echo '<form method="post" action="process_form.php">';
    echo '<input type="hidden" name="id" value="' . $row['id'] . '">';
    echo '<input type="submit" value="Submit">';
    echo '</form>';
}
?>