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

Asked

Viewed 15,493 times

4

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

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

while ($rows = mysql_fetch_array($searc)) {
$soma_das_visu = array_sum($rows); 
}
?>
  • 3

    Try to add the right key values: $total= 0;&#xA;while(....){&#xA;$total += $rows['valor']

3 answers

5


You can handle this straight 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 '];
  • Thankful, I couldn’t find any options in my mind: now I have two. I’ll use it directly from the query. It’s done!

  • Nice! Nice to have helped.

3

Array_sum does not work as expected pq mysql_query() returns only a row and not the entire array, for example:

SELECT valor FROM tabela

will be returned to line:

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

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

Depending on how is your query the answer from @Leandro Curious 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;
  • 1

    I will use the example of the Curious even, grateful.

2

Place the respective 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']; 
}
?>
  • 2

    So you won’t add anything up, you’ll only know the result of the last element.

  • @Jorge B. Really Jorge. I edited the post, because I went unnoticed in array_sum.

  • the reply of @lost ;)

  • Thank you Lucas and Jorge. It’s done!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.