In PHP, what are some common pitfalls to avoid when dealing with MySQL queries and loops?

One common pitfall when dealing with MySQL queries and loops in PHP is not properly freeing up resources after executing a query. This can lead to memory leaks and degraded performance. To avoid this, always remember to free the result set after fetching the data.

// Incorrect way: Not freeing the result set
$result = mysqli_query($connection, "SELECT * FROM table");
while ($row = mysqli_fetch_assoc($result)) {
    // Process data
}
// Missing mysqli_free_result($result);

// Correct way: Freeing the result set
$result = mysqli_query($connection, "SELECT * FROM table");
while ($row = mysqli_fetch_assoc($result)) {
    // Process data
}
mysqli_free_result($result);