Home >Database >Mysql Tutorial >How to Calculate Column Sums in MySQL using PHP?

How to Calculate Column Sums in MySQL using PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 07:25:06992browse

How to Calculate Column Sums in MySQL using PHP?

How to Retrieve Column Sum in MySQL Using PHP

Query-Based Approach:

To efficiently retrieve the sum of a column, leverage SQL's built-in aggregation function:

SELECT SUM(column_name) FROM table_name;

PDO Implementation:

// Prepare the query
$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');

// Execute the query
$stmt->execute();

// Fetch the results
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// Retrieve the sum
$sum = $row['value_sum'];

mysqli Implementation:

// Execute the query
$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes');

// Fetch the results
$row = mysqli_fetch_assoc($result);

// Retrieve the sum
$sum = $row['value_sum'];

Note:

  • The mysql_fetch_assoc and mysql_query functions are deprecated in PHP 5.5 and above. Consider using PDO or mysqli instead.
  • The sample code assumes that $conn is a pre-established MySQL connection.
  • The column name and table name may vary based on your database schema.

The above is the detailed content of How to Calculate Column Sums in MySQL 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