Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SUM function

Tags:

php

mysql

I have a table like following:

id    q_id         value  
------------------------
1     2            5 
2     2            NULL 
3     2            5 
4     2            NULL 
5     4            2 
6     4            NULL 
7     4            2 
8     4            NULL 

What I want is to get the sum of (for example) all value where q_id = 2

    $sq = mysql_query("SELECT SUM(value) AS sum FROM  table WHERE q_id = 2)or die(mysql_error());
   while($row = mysql_fetch_array($sq)){
    $sum = $row['sum'];
     }
  echo $sum."<br>";

But I'm getting

5
5

But what I want is the sum of the value and expecting 10 instead.

Thank you for helping.

like image 347
Jonas Willander Avatar asked Sep 05 '25 17:09

Jonas Willander


1 Answers

If you're going to loop over the result set anyway, why not just use

SELECT value FROM table WHERE q_id=2

then sum up those values using the while loop? Something like:

while($row = mysql_fetch_array($sq)) {     $sum += $row['value']; } echo $sum."<br>";

Edit: also, as Jason McCreary said above, you should look into an alternate method of querying the database. I would suggest searching php.net for "PDO", which is very easy to use.

like image 54
itsmequinn Avatar answered Sep 07 '25 08:09

itsmequinn