What are the potential pitfalls of using while loops to output query results in PHP, and how can they be avoided?
Using while loops to output query results in PHP can lead to potential pitfalls such as infinite loops if not handled properly. To avoid this, it is important to ensure that the loop has a proper exit condition based on the number of rows returned by the query.
// Example of using a while loop to output query results safely
// Execute the query
$result = mysqli_query($conn, "SELECT * FROM table");
// Check if there are rows returned
if(mysqli_num_rows($result) > 0) {
// Output the results using a while loop
while($row = mysqli_fetch_assoc($result)) {
// Output each row data here
echo $row['column_name'] . "<br>";
}
} else {
echo "No results found.";
}