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 with PHP
How to calculate the sum of data in a certain field in mysql in PHP
php
Use foreach
to traverse and accumulate the fields you want to sum
mysql
Just 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