What is the correct way to calculate the sum of values in a MySQL table using PHP?

To calculate the sum of values in a MySQL table using PHP, you can use a SQL query to fetch the sum of the desired column from the table. You can then retrieve the sum value using PHP and display it as needed.

<?php
// Connect to MySQL 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 sum of values in a specific column
$sql = "SELECT SUM(column_name) AS total_sum FROM table_name";
$result = $conn->query($sql);

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

$conn->close();
?>