What are the potential pitfalls of using while loops to display data from a MySQL database in PHP?
One potential pitfall of using while loops to display data from a MySQL database in PHP is the risk of infinite loops if the loop condition is not properly set. To avoid this, it is important to ensure that the loop condition is based on the result set fetched from the database and that the loop is properly terminated when all data has been displayed.
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Fetch data from database
$result = $mysqli->query("SELECT * FROM table");
// Display data using while loop
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
// Close connection
$mysqli->close();