What are some best practices for efficiently adding values from multiple items in a MySQL database using PHP?

To efficiently add values from multiple items in a MySQL database using PHP, you can use a SQL query to calculate the sum directly in the database rather than fetching all the values and summing them in PHP. This approach reduces the amount of data transferred between the database and the PHP script, resulting in better performance.

// 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 calculate the sum of values from multiple items
$sql = "SELECT SUM(value_column) AS total_sum FROM table_name WHERE condition_column = 'condition_value'";

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

if ($result->num_rows > 0) {
    // Output the total sum
    $row = $result->fetch_assoc();
    echo "Total sum: " . $row["total_sum"];
} else {
    echo "No results found";
}

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