How can the code snippet be improved to efficiently retrieve and display group names instead of IDs in the output?

The issue can be solved by modifying the SQL query to join the groups table and retrieve the group names instead of IDs. This can be achieved by using a JOIN clause in the SQL query to combine the users and groups tables based on the group_id column. Then, in the PHP code, we can access the group name from the result set and display it in the output.

<?php
// SQL query to retrieve user data along with group names
$sql = "SELECT users.id, users.name, groups.name AS group_name
        FROM users
        JOIN groups ON users.group_id = groups.id";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "User ID: " . $row["id"]. " - Name: " . $row["name"]. " - Group: " . $row["group_name"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>