1

The student is back. Thanks for you help an patience ;)

I'm using a foreach loop like this:

foreach ($value as $val)
{
//coming from database, from a select query:
$points = $row['points'];  

//now I want to update another database table:  
 $sql = "update user set totalpoints=".$points." where userid=".$uid." ";

//but by doing this, table user is updated with the value of $points in the last iterarion 

}

What do I have to do to update my table with the summation of $points and not with the value of the last iteration?

Thanks again

2
  • Do you mean iterate over all rows, sum all the points values, and insert a new row with the total? Commented Feb 22, 2011 at 16:34
  • SQL has a SUM() function that you can use. It will be faster than querying each row in PHP. Commented Feb 22, 2011 at 16:36

3 Answers 3

3

Not 100% sure but it seems you want:

$sum = 0;

foreach ($value as $val) {
    $sum += $row['points'];  
}

$sql = "update user set totalpoints=".$sum." where userid=".$uid;
Sign up to request clarification or add additional context in comments.

Comments

2
$points = 0;
while ($row = mysq_fetch_array()) // from where you are getting row
{
//coming from database, from a select query:
$points += $row['points'];  

}


//now I want to update another database table:  
 $sql = "update user set totalpoints=".$points." where userid=".$uid." ";

Comments

1

You should do it all in one query

I suppose your original query was something like SELECT * FROM matches WHERE userid='$uid' (whatever) so instead do something like UPDATE user SET totalpoints=(SELECT SUM(points) FROM matches WHERE userid='$uid' GROUP BY userid) WHERE userid='$uid' (Probably it would not fit your exact problem but I hope you get the idea)

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.