Home >Backend Development >PHP Tutorial >How to calculate the sum of data in a certain field in mysql in PHP

How to calculate the sum of data in a certain field in mysql in PHP

WBOY
WBOYOriginal
2016-08-23 09:17:452348browse

How to calculate the sum of data in a certain field in mysql with PHP

Reply content:

How to calculate the sum of data in a certain field in mysql in PHP

  • phpUse foreach to traverse and accumulate the fields you want to sum

  • mysqlJust use SUM

<code>SELECT sum(`field_name`) 
FROM `table`</code>

Since you can use MySQL, why not just use MySQL’s sum

Write a foreach loop in php and compile it again

Borrowing from the questioner’s question, is mysql’s sum faster or PHP’s foreach faster?

foreach calculates the sum of data
foreach($income as $key=>$val){

<code>        $total+= $val['xx'];          
    }</code>

mysql’s sum() function

Yes, why not use the SUM function, select SUM('field') where...; If the data is special, just use some functions in mysql to format it.

If it is a one-dimensional array, directly use array_sum
If it is a two-dimensional array, you can use array_column, array_sum
It feels good to do it through mysql

The result is usually an array. You can just count($data) to find the total number of data

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