How can duplicate user IDs in a MySQL table be handled when calculating total points for each user in PHP?

When calculating total points for each user in PHP from a MySQL table, duplicate user IDs can cause inaccuracies in the total points calculation. To handle this issue, we can use the GROUP BY clause in our SQL query to group the points by user ID before calculating the total points in PHP.

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

// Query to calculate total points for each user
$query = "SELECT user_id, SUM(points) AS total_points FROM points_table GROUP BY user_id";
$result = mysqli_query($connection, $query);

// Loop through the results and display total points for each user
while($row = mysqli_fetch_assoc($result)) {
    echo "User ID: " . $row['user_id'] . " - Total Points: " . $row['total_points'] . "<br>";
}

// Close database connection
mysqli_close($connection);
?>