How can PHP be used to sum up values from a database table based on a specific user ID?

To sum up values from a database table based on a specific user ID, you can use SQL queries to retrieve the relevant data and then use PHP to calculate the sum. First, query the database to select the values based on the user ID. Then, iterate through the results and sum up the values. Finally, display or use the total sum 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);
}

// User ID for which we want to sum up values
$user_id = 1;

// Query to select values based on user ID
$sql = "SELECT value FROM table_name WHERE user_id = $user_id";
$result = $conn->query($sql);

// Initialize total sum
$total_sum = 0;

// Sum up the values
while($row = $result->fetch_assoc()) {
    $total_sum += $row['value'];
}

// Display the total sum
echo "Total sum for user ID $user_id is: $total_sum";

// Close the connection
$conn->close();
?>