What are common pitfalls when using while loops in PHP for database queries?

One common pitfall when using while loops in PHP for database queries is forgetting to fetch the next row inside the loop, which can result in an infinite loop or skipping rows. To solve this issue, always remember to call the fetch method inside the loop to move the pointer to the next row.

// Incorrect way - missing fetch inside the loop
$result = $conn->query("SELECT * FROM table");
while ($row = $result->fetch_assoc()) {
    // Process data
}

// Correct way - fetch inside the loop
$result = $conn->query("SELECT * FROM table");
while ($row = $result->fetch_assoc()) {
    // Process data
    $result->fetch_assoc(); // Fetch the next row
}