PHP:循环内需要求和

发布于 2024-10-18 12:19:21 字数 461 浏览 1 评论 0原文

那个学生回来了。感谢您的耐心帮助;)

我正在使用这样的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

飘然心甜 2024-10-25 12:19:21

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

$sum = 0;

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

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

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;
海的爱人是光 2024-10-25 12:19:21
$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." ";
$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." ";
尬尬 2024-10-25 12:19:21

你应该在一个查询中完成这一切

我想你的原始查询类似于 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 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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文