What are the potential pitfalls of using a while loop to output database results in PHP?

Using a while loop to output database results in PHP can potentially lead to infinite loops if not handled properly. To avoid this issue, it is important to fetch each row from the database within the loop and check if there are any remaining rows before continuing the loop. This ensures that the loop will terminate once all results have been processed.

// Fetch data from the database
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

// Check if there are any rows to process
if(mysqli_num_rows($result) > 0) {
    // Output data using a while loop
    while($row = mysqli_fetch_assoc($result)) {
        // Output data here
    }
} else {
    echo "No results found";
}