In the provided code snippet, what improvements can be made to optimize the loop and database queries for better performance?

The issue with the current code is that it is performing a database query inside a loop, which can be inefficient and slow down the performance. To optimize this, we can fetch all the data we need from the database in a single query before entering the loop. This way, we reduce the number of database queries and improve the overall performance.

// Fetch all data from the database in a single query
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);

// Check if the query was successful
if ($result) {
    // Loop through the fetched data
    while ($row = mysqli_fetch_assoc($result)) {
        // Process each row
        echo $row['username'] . "<br>";
    }
} else {
    echo "Error: " . mysqli_error($connection);
}

// Free the result set
mysqli_free_result($result);