What are the potential pitfalls of overwriting variables in a while loop when fetching data from a MySQL query in PHP?

Overwriting variables in a while loop when fetching data from a MySQL query in PHP can lead to data loss or unexpected behavior. To avoid this issue, you can store the fetched data in an array or object for each iteration of the loop.

// Fetch data from MySQL query
$result = mysqli_query($conn, "SELECT * FROM table");

// Initialize an empty array to store the fetched data
$data = [];

// Loop through the results and store them in the data array
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

// Now you can access the fetched data from the $data array
foreach ($data as $row) {
    // Process the data here
}