PHP:循环内部需要求和

时间:2011-02-22 16:30:57

标签: php foreach iteration

学生回来了。谢谢你帮助耐心;)

我正在使用这样的foreach循环:

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 

}

如何使用$ points的总和而不是上次迭代的值来更新表格,我该怎么做?

再次感谢

3 个答案:

答案 0 :(得分:3)

不是100%肯定,但似乎你想要:

$sum = 0;

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

$sql = "update user set totalpoints=".$sum." where userid=".$uid;

答案 1 :(得分: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." ";

答案 2 :(得分:1)

您应该在一个查询中完成所有操作

我认为您的原始查询类似于SELECT * FROM matches WHERE userid='$uid'(无论如何),所以请执行类似UPDATE user SET totalpoints=(SELECT SUM(points) FROM matches WHERE userid='$uid' GROUP BY userid) WHERE userid='$uid'的操作(可能它不适合您的确切问题,但我希望您能得到这个想法)