我是PHP和mysql的新手,我正在尝试构建一个表。但是,我有一个非常有趣的错误,我无法解决。
代码:
//Initializing mysql queries
//-----------------------SELECTING GOALS------------
$sql= "SELECT * FROM goals";
$records = mysql_query($sql);
//-----------------------SELECTING SERVICES---------
$sql2= "SELECT * FROM services";
$records2 = mysql_query($sql2);
//----------------SELECTING THE JUNCTION----------
$sql3 = "SELECT services.sid AS sid, services.name, objectives.oid
FROM services, objectives, servo
WHERE servo.s_id = services.id AND servo.obj_id = objectives.id";
$records3 = mysql_query($sql3);
$sql4 = "SELECT oid, gid, statement, GROUP_CONCAT(DISTINCT gid) AS GOID
FROM goals, objectives, obgoals
WHERE obgoals.go_id = goals.id AND obgoals.ob_id = objectives.id
GROUP BY oid";
$records4 = mysql_query($sql4);
<?php
while ($product = mysql_fetch_assoc($records2)) {
echo "<tr>";
$sid = $product['sid'];
$service = $product['name'];
echo "<td><a href='objectives.php?sid=" . $sid . "&service=" . $service . "'>" . $product['sid'] . "</a> </td>";
echo "<td>".$product['name']."</td>";
echo "<td>";
while ($g4services = mysql_fetch_assoc($records)) {
echo $g4services['gid'];
}
echo"</td>" ;
}
?>
基本上,我的表有30行3列,最后一列应该打印出数据库中的值,这部分是由这段代码完成的
while ($g4services = mysql_fetch_assoc($records)) {
echo $g4services['gid'];
}
但是,它不是打印每一行的结果,而是仅打印第一行的结果,基本上是第一个while循环运行并创建具有30行的表,但第二个while循环仅打印第一行的值只排。基本上这种情况正在发生:
|SID|Name Of Service| Objectives|
-------------------------------
|S1| Service 1 | make the best cars|
|s2| Service 2 | |
|s3| Service 3 | |
|s4| Service 5 | |
|s5| Service 5 | |
.....
.....
....
|s30| Service30 | |
由于某种原因,我的目标列没有填充while循环,它只适用于第一行。如果有人可以帮助我使用while循环来打印每行的值,那将是巨大的帮助。我将非常感激。感谢。
答案 0 :(得分:0)
您的第二个while循环不是必需的。每一行都在奔跑。去掉它。然后,对于每一行,您必须找到匹配的条目,并仅回显该条目。
echo $g4services['gid']
我不知道如何纠正它,因为我不知道两者之间的关系。
答案 1 :(得分:0)
问题是您在外部$records
循环的第一次迭代期间正在阅读while
的所有结果。在将来的迭代中,不再有行,因此内部while
循环立即完成。
您可以将这些结果一次读入循环外的变量,然后在循环中显示该变量:
$all_g4services = '';
while ($g4services = mysql_fetch_assoc($records)) {
$all_g4services .= $g4services['gid'];
}
while ($product = mysql_fetch_assoc($records2)) {
echo "<tr>";
$sid = $product['sid'];
$service = $product['name'];
echo "<td><a href='objectives.php?sid=" . $sid . "&service=" . $service . "'>" . $product['sid'] . "</a> </td>";
echo "<td>".$product['name']."</td>";
echo "<td>$all_g4services;</td>" ;
}