What is the purpose of using a While loop in PHP for displaying information from a database?

When displaying information from a database in PHP, a While loop is commonly used to iterate through the result set and output each row of data. This is necessary because the number of rows returned by a database query can vary, and a While loop allows us to process each row dynamically until there are no more rows left to display.

<?php
// Assume $conn is the database connection and $query is the SQL query
$result = mysqli_query($conn, $query);

// Check if there are any rows returned
if (mysqli_num_rows($result) > 0) {
    // Output data of each row using a While loop
    while($row = mysqli_fetch_assoc($result)) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

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