Jump to content

[SOLVED] MySQL SUM() problem


Andy17

Recommended Posts

Things you need to know

 

I have a table called "points" where I want to select a given user's rows. Each row has a number in the column "points" and I want to add all these numbers and get the total amount. So, here is a simple example:

 

id       |       username        |      points
---------|-----------------------|------------
0        |       test1           |      25
1        |       test2           |      10
2        |       test1           |      15
3        |       test1           |      50

 

In the example above, I would want to choose the rows where the username is "test1" (0, 2, 3) and add the points (25 + 15 + 50 = 90). This is the code I have so far:

 

<?php

$username = $_SESSION['username'];
$findpts = "SELECT points, SUM(points) FROM points WHERE username = '$username' GROUP BY points";
$findptsresult = mysql_query($findpts) or die(mysql_error());

if ($findptsresult)

{

          // Unfortunately, the following only adds two numbers and totally leaves out any more numbers after that
          $row = mysql_fetch_array($findptsresult);
          echo $row['SUM(points)'];

}

?>

 

I was thinking of going something like this, but I am missing a big part of code. :P

 

<?php

// First code = same as above

while($row = mysql_fetch_array($findptsresult))

{

// Some code here 

}

?>

 

I might be getting at this from a completely wrong angle, I'm not sure. Any ideas on how to do this?

 

Thank you!

Link to comment
https://forums.phpfreaks.com/topic/127583-solved-mysql-sum-problem/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.