0

我有一个通过数据库运行并将所有内容输出到 php 页面的代码。

$avg = mysql_query("SELECT subject, gradeone, gradetwo, gradethree, ((gradeone + gradetwo + gradethree) / 3) as average FROM grades");


$q = mysql_query("SELECT * FROM newstudent AS n JOIN grades AS g ON n.id = g.id ORDER BY n.id") or die (mysql_error());

$last_student = null;

while ($row = mysql_fetch_assoc($q))
    {
        if ($row['id'] !== $last_student)
        {
            $last_student = $row['id'];
            echo "Student ID: ".$row['id']."<br/>";
            echo "First Name: ".$row['firstname']."<br/>";
            echo "Last Name: ".$row['lastname']."<br/>";
            echo "Email: ".$row['email']."<br/>";
            echo "<br/>";
        }
            print "<table id=reporttable>"; 

            print "<tr id=toprow> <td>subject</td> <td>gradeone</td> <td>gradetwo</td> <td>gradethree</td> <td>average</td></tr>"; 

            print   "<tr>";          

                print   " <td>";    
                    print   $row["subject"];
                print   "</td>"  ;

                print   " <td>";    
                    print   $row["gradeone"];
                print   "</td>"  ;

                print   " <td>";    
                    print   $row["gradetwo"];
                print   "</td>"  ;

                print   " <td>";    
                    print   $row["gradethree"];
                print   "</td>"  ;

                while ($r = mysql_fetch_array($avg))
                {
                    print   " <td>";    
                        print   $r['average'];
                    print   "</td>"  ;
                }

            print   " </tr>";   
            print "</table>";             

}?>

期望的结果应该是这样的

期望的结果 以下代码的结果很好,但只有 1 个小问题。

假设第二个 while 循环计算平均值并在新行中输出每条记录。相反,它这样做:

错误的结果

任何人都知道一种方法可以使这些平均成绩中的每一个都与学生的每一行一致吗?

4

1 回答 1

2
$q = mysql_query("
    SELECT
        n.id,
        n.firstname, 
        n.lastname,
        n.email,
        g.gradeone, 
        g.gradetwo, 
        g.gradethree, 
        ((g.gradeone + g.gradetwo + g.gradethree) / 3) AS average
    FROM
        newstudent n JOIN grades g USING (id)
    ORDER BY
        n.id
") or die (mysql_error());

尝试使用此查询,然后在一个循环中输出结果 - 删除它

while ($r = mysql_fetch_array($avg))

带着它的大括号。

留下这样的东西:

....
print "<td>$row['gradetwo']</td>";
print "<td>$row['gradethree']</td>";

print "<td>$row['average']</td>";
....
于 2013-11-01T14:56:34.677 回答