PHP:循环内需要求和
那个学生回来了。感谢您的耐心帮助;)
我正在使用这样的 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 的总和而不是最后一次迭代的值来更新我的表?
再次感谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不是 100% 确定,但似乎你想要:
Not 100% sure but it seems you want:
你应该在一个查询中完成这一切
我想你的原始查询类似于 SELECT * FROM matches WHERE userid='$uid' (无论如何),所以改为执行类似 UPDATE user SET Totalpoints= 的操作(SELECT SUM(points) FROM matches WHERE userid='$uid' GROUP BY userid) WHERE userid='$uid' (可能它不适合您的确切问题,但我希望您明白)
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 likeUPDATE 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)