What are some best practices for handling MySQL queries in PHP loops to avoid performance issues?

When handling MySQL queries in PHP loops, it is important to avoid executing a query inside the loop as it can lead to performance issues due to the overhead of establishing a new database connection each time. Instead, it is recommended to fetch all the necessary data before entering the loop and then iterate over the fetched results within the loop.

// Fetch data before entering the loop
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

if($result) {
    while($row = mysqli_fetch_assoc($result)) {
        // Process each row within the loop
    }
} else {
    echo "Error: " . mysqli_error($connection);
}

// Free the result set
mysqli_free_result($result);