How to sum the results of an array brought from the database in PHP?

4

I'm doing this, but what's being added is the number of rows and not the values of the "something" field.

<?php 
$searc= mysql_query ("SELECT algo FROM lugar")  or die (mysql_error());

while ($rows = mysql_fetch_array($searc)) {
$soma_das_visu = array_sum($rows); 
}
?>
    
asked by anonymous 30.04.2014 / 15:32

3 answers

5

You can handle this directly from your query

SELECT SUM(nome_coluna) AS valor_soma FROM nome_tabela;

You can even add other columns ...

SELECT SUM(nome_coluna1 + nome_coluna2) AS valor_total_soma FROM nome_tabela;

In php try something like:

$result = mysql_query('SELECT SUM(nome_coluna1) AS valor_soma FROM nome_tabela'); 
$row = mysql_fetch_assoc($result); 
$sum = $row['valor_soma '];
    
30.04.2014 / 15:51
3

The array_sum does not work as expected because mysql_query() returns only one row and not the entire array, for example:

SELECT valor FROM tabela

will be returned to line :

Array
(
    [0] => 150
    [valor] => 150
)

When applied to the array_sum the result will be 300 because it is adding the value of the two keys and also pq $soma_das_visu is overwritten with every loop of the while.

Depending on how your query is, the response from @Leandro Curioso is the most practical. Or you can use a variable to save the total:

$total = 0;
while ($rows = mysql_fetch_array($searc)) {
   $total += $rows['valor']; 
}
 echo 'total: '+ total;
    
30.04.2014 / 16:06
2

Place the corresponding field 'algo' :

<?php 
$searc= mysql_query ("SELECT algo FROM lugar")  or die (mysql_error());

$soma_das_visu = 0;
while ($rows = mysql_fetch_array($searc)) {
$soma_das_visu += $rows['algo']; 
}
?>
    
30.04.2014 / 15:37