0

我似乎无法弄清楚为什么这个脚本会这样做,所以我需要有更多经验/更好的眼睛的人来告诉我问题是什么。我似乎无法在网上其他地方找到任何东西,但我的搜索字词可能是错误的。这组 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!

为什么是四个?为什么?!我尝试了几种不同的方法来修复它(对不起,我不记得我现在尝试了什么),但无济于事。

4

5 回答 5

0

问题是您正在遍历列。删除 foreach 循环,你应该会很好。

于 2013-02-20T20:06:48.897 回答
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/>";
         }
     //}
于 2013-02-20T20:07:05.777 回答
0

您可以通过直接从数据库中查询所需内容并迭代简单结果来简化代码。

SELECT name, username, sum(gradpoint.totalseconds) as total FROM name_records, gradpoint where name_records = gradpoint.username group by gradpoint.username
于 2013-02-20T20:09:57.340 回答
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";

可能工作

于 2013-02-20T20:10:17.087 回答
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。

于 2013-02-20T20:18:58.633 回答