What is the importance of using a while loop in PHP for database output and how does it affect the display of multiple entries?
When retrieving data from a database in PHP, using a while loop is crucial to iterate through multiple entries and display them on the webpage. Without a while loop, only the first entry would be displayed, as the loop allows for fetching and displaying each record until there are no more left.
// Connect to database and retrieve data
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT * FROM table");
// Display data using a while loop
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
// Close database connection
$conn->close();