What is the purpose of using a while loop to output data from a database table in PHP?

When outputting data from a database table in PHP, a while loop is used to iterate through the result set retrieved from the database query. This loop allows you to fetch each row of data one by one and output it to the webpage. By using a while loop, you can dynamically display all the data from the database table without knowing the exact number of rows in advance.

<?php
// Connect to database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Query to select data from table
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

// Output data using a while loop
while ($row = mysqli_fetch_assoc($result)) {
    echo "Name: " . $row['name'] . "<br>";
    echo "Age: " . $row['age'] . "<br>";
    // Add more fields as needed
}

// Close database connection
mysqli_close($connection);
?>