How can the code snippet be optimized to improve performance and reduce unnecessary database queries?

The issue with the current code is that it is making unnecessary database queries within the loop for each user. To optimize performance and reduce unnecessary queries, we can fetch all user data in a single query outside the loop and then iterate over the results within the loop.

// Fetch all user data in a single query
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Iterate over the users array
foreach ($users as $user) {
    // Use the user data without querying the database again
    echo "User ID: " . $user['id'] . ", Name: " . $user['name'] . "<br>";
}