本文介绍了while循环并在mysql php中加入输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个遍历数据库并将所有内容输出到php页面的代码.
I have a code that runs through database and outputs everything to a php page.
$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>";
}?>
所需的结果应如下所示
以下代码的结果很棒,但是只有一个小问题.
the outcome from the following code is great, but there is only 1 minor issue.
第二个while循环假定是计算平均值并在新行输出每个记录.而是这样做:
the 2nd while loop is suppose to be calculating the average and outputting each record at a new row. instead it does this:
任何人都知道一种方法来使这些平均成绩中的每一项都与学生的每一行相伴吗?
anyone knows a way to make it that each one of those average grades goes along with each row for students?
推荐答案
$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());
尝试使用此查询,然后在一个循环中输出结果-删除该
Try to use this query and then output the results in one single loop - remove that
while ($r = mysql_fetch_array($avg))
及其大括号.
留下这样的东西:
....
print "<td>$row['gradetwo']</td>";
print "<td>$row['gradethree']</td>";
print "<td>$row['average']</td>";
....
这篇关于while循环并在mysql php中加入输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!