0

With the first query in the following code I am looking for the checkings made in Berlin under the game number two.

With the second query I want to give points for each of the checkings.

As you will see I am using the function SUM. But let's say that I have 2 checkings and the points for each checking are 50. Well, instead of echoing 100, with this code I echo 5050

What is wrong with it?

Thanks a lot

THE CODE IS CORRECTED AND WORKING, JUST IN CASE SOMEBODY NEEDS IT. Thanks to all

       $querya = "SELECT * FROM checkins where gamesid=2 and city='Berlin'";
 $resulta = mysql_query($querya) or die(mysql_error());

 $sumOfPoints = 0;
 while($rowa = mysql_fetch_array($resulta)){

      $n = $rowa['venuesid'];
      $queryb = "SELECT venuesid, SUM(points) as sumpoints from venues where venuesid='".$n."' GROUP BY venuesid ORDER BY venuesid";
      $resultb = mysql_query($queryb) or die(mysql_error());

      while($rowb = mysql_fetch_array($resultb)){

           $sumOfPoints +=  $rowb['sumpoints'];

      }

 }


  echo "Total points is $sumOfPoints<br/>";
2
  • Why would it echo 100? If you have two checkins, then the outer loop will always fire twice. If anything you might expect 100100. Commented Mar 3, 2011 at 16:16
  • this should be echo out of the while loop or else it will keeps on loops, $rowb = mysql_fetch_array($resultb); echo $rowb['SUM(points)']; Commented Mar 3, 2011 at 16:18

3 Answers 3

1

Some suggestions

  1. Use SUM(points) AS sum (only for clarity when use the sum)

  2. Check that points are numerical fields not varchar.

Sign up to request clarification or add additional context in comments.

Comments

1

points must be a string, you need to cast it

SUM(cast(points) as int)

and then follow Gaurav's point about labeling the compute

Comments

0

You're getting 5050 because your script is echoing 50 in two iterations of the loop.

From the looks of it, your second query's GROUP BY clause is not grouping on venuesid when it should be. So, first try changing your GROUP BY clause to:

GROUP BY venuesid

If that doesn't give you the result you're looking for, then you should try running your query directly against the database with a static value for venuesid to see what you get back from it, then perhaps update your question and we can take it from there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.