我似乎无法弄清楚为什么这个脚本会这样做,所以我需要有更多经验/更好眼睛的人来告诉我这是什么问题。我似乎无法在网上找到任何其他内容,但我可能会误解我的搜索字词。这组While / Foreach循环工作得很好,除了它四次吐出同一行:
$squery = "SELECT username, name FROM name_records";
$sresult = mysql_query($squery);
while($srow = mysql_fetch_array($sresult)) {
foreach ($srow as $scell) {
$username = $srow['username'];
$name = $srow['name'];
$queryi = "SELECT SUM(totalseconds) FROM gradpoint WHERE username = '$username'";
$resulti = mysql_query($queryi) or die(mysql_error());
while($rowi = mysql_fetch_array($resulti)){
$total = $rowi['SUM(totalseconds)'];
$minutes = $total / 60;
echo $name ." has worked for " .$minutes ." minutes today! Good jorb!<p/>";
}
}
}
如果name_records表中的前两个条目是“Bob Ross,br01234”和“Alfred Hitchcock,ah43210”,那么上面的代码就会吐出来:
Bob Ross has worked for 342 minutes today! Good jorb!
Bob Ross has worked for 342 minutes today! Good jorb!
Bob Ross has worked for 342 minutes today! Good jorb!
Bob Ross has worked for 342 minutes today! Good jorb!
Alfred Hitchcock has worked for 187 minutes today! Good jorb!
Alfred Hitchcock has worked for 187 minutes today! Good jorb!
Alfred Hitchcock has worked for 187 minutes today! Good jorb!
Alfred Hitchcock has worked for 187 minutes today! Good jorb!
为什么四个?为什么?!我尝试了几种不同的方法来解决它(对不起,我不记得我现在尝试过的),但无济于事。
答案 0 :(得分:0)
问题是你在遍历列。删除foreach循环,你应该很好。
答案 1 :(得分:0)
我认为问题来自于foreach:
//foreach ($srow as $scell) {
$username = $srow['username'];
$name = $srow['name'];
$queryi = "SELECT SUM(totalseconds) FROM gradpoint WHERE username = '$username'";
$resulti = mysql_query($queryi) or die(mysql_error());
while($rowi = mysql_fetch_array($resulti)){
$total = $rowi['SUM(totalseconds)'];
$minutes = $total / 60;
echo $name ." has worked for " .$minutes ." minutes today! Good jorb!<p/>";
}
//}
答案 2 :(得分:0)
您可以通过直接从数据库查询所需内容并迭代简单结果来简化代码。
SELECT name, username, sum(gradpoint.totalseconds) as total FROM name_records, gradpoint where name_records = gradpoint.username group by gradpoint.username
答案 3 :(得分:0)
您可以通过某种加入和群组实现您的目标。 类似的东西:
$squery = "SELECT nr.username, nr.name, SUM(g.totalseconds) as totsec FROM name_records nr, gradpoint g
WHERE g.username=nr.username
GROUP BY nr.username,nr.name";
可能会工作
答案 4 :(得分:0)
$query = "
SELECT u.*, (SUM(g.totalseconds) / 60) as sum
FROM name_records u
JOIN gradpoint g
ON u.username = g.username
GROUP BY u.username;
";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo $row['name'] . " has worked for " . $row['sum'] . " minutes today! Good jorb!<br/>";
}
还包括除以60。