What role does the while loop play in fetching data from a MySQL database in PHP?

When fetching data from a MySQL database in PHP, the while loop is used to iterate through the result set returned by a query. This loop allows you to fetch each row of data one at a time until there are no more rows left to retrieve. By using the while loop, you can process each row of data individually and perform any necessary operations on it.

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

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

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

// Fetch data using a while loop
while ($row = mysqli_fetch_assoc($result)) {
    // Process each row of data
    echo "Name: " . $row['name'] . "<br>";
    echo "Age: " . $row['age'] . "<br>";
}

// Close connection
mysqli_close($connection);