Home >Backend Development >PHP Tutorial >How to Calculate the Sum of a MySQL Column Using PHP?

How to Calculate the Sum of a MySQL Column Using PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-02 13:25:15658browse

How to Calculate the Sum of a MySQL Column Using PHP?

How to Calculate Column Sum in MySQL using PHP

Aggregating data in SQL can be achieved using aggregate functions like SUM(). To find the sum of values stored in a MySQL column, there are multiple approaches available in PHP.

Using SQL Query Directly

The simplest method involves performing the calculation directly in the MySQL query:

SELECT SUM(column_name) FROM table_name;

Using PDO

PDO provides a modern and secure way to connect to MySQL. Here's how to calculate the sum using PDO:

$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];

Using MySQLi

Another option is to use the mysqli extension:

$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes'); 
$row = mysqli_fetch_assoc($result); 
$sum = $row['value_sum'];

Handling Errors

mysql_fetch_assoc() is deprecated and should not be used in modern PHP code. Instead, use mysqli_fetch_assoc or PDOStatement::fetch to retrieve the calculated value from the database.

The above is the detailed content of How to Calculate the Sum of a MySQL Column Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn