How can one efficiently retrieve and sum points for each user ID from a MySQL database using PHP?

To efficiently retrieve and sum points for each user ID from a MySQL database using PHP, you can use a SQL query to fetch the data and then iterate through the results to calculate the sum for each user ID. You can store the sums in an associative array with the user ID as the key. Finally, you can display or use the sums as needed.

<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query to retrieve points for each user ID
$sql = "SELECT user_id, SUM(points) AS total_points FROM points_table GROUP BY user_id";
$result = $conn->query($sql);

$points_sum = array();

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        $points_sum[$row["user_id"]] = $row["total_points"];
    }
} else {
    echo "0 results";
}

// Display or use the sums as needed
foreach ($points_sum as $user_id => $total_points) {
    echo "User ID: " . $user_id . ", Total Points: " . $total_points . "<br>";
}

$conn->close();
?>