How can a while loop be used to properly fetch and store multiple rows from a MySQL query in PHP?

When fetching and storing multiple rows from a MySQL query in PHP, a while loop can be used to iterate through each row returned by the query and store them in an array or process them individually. Inside the while loop, the fetch_assoc() method can be used to fetch each row as an associative array, which can then be stored or processed as needed.

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

// Query to fetch multiple rows
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Initialize an empty array to store the fetched rows
$rows = array();

// Use a while loop to fetch and store each row
while ($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row; // Store each row in the array
}

// Close the database connection
mysqli_close($connection);

// Process the fetched rows as needed
foreach ($rows as $row) {
    // Process each row here
}