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

WBOY
Release: 2016-08-23 09:17:45
Original
2319 people have browsed it

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>
Copy after login

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>
Copy after login

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template