如何在<表>中有两个 while 循环


How to have two while loops in a <table>?

<?php
if ($result->num_rows > 0) {
echo"<fieldset style=width:300px;>
<center><table>
<table cellpadding=10;>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Room Number</th>
<th></th>
</tr>
</fieldset>";
while ($row = $result->fetch_assoc()){
echo "<tr><td>" . $row["firstname"] . 
"</td><td>" . $row["lastname"] .  
"</td>";
}
while ($row = $result2->fetch_assoc()){
echo "</td><td>" . $row["roomnumber"] . "</td></td>" . "</td><td>";
}
echo "</table></center>";
} else {
echo "0 results";
}
?>

如何将所有结果放在表中?对于第一个结果,名字和姓氏分别正确显示在标题下,但是,对于第二个结果,房间号未正确显示在标题下方,而是显示在其他地方。我该如何解决这个问题?

我认为您的SQL查询可以通过使用JOIN来完成,例如:

SELECT p.FirstName, p.LastName, r.RoomNumber
FROM Persons p
LEFT JOIN Rooms r ON r.PersonID=p.PersonID

使用单个查询时,您将需要单个while来显示结果。

使用 jQuery:

<?php
$i = 1;
if ($result->num_rows > 0) {
echo"<fieldset style=width:300px;>
<center><table>
<table cellpadding=10;>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Room Number</th>
<th></th>
</tr>
</fieldset>";
while ($row = $result->fetch_assoc()){
echo "<tr><td>" . $row["firstname"] . 
"</td><td>" . $row["lastname"] .  
"</td><td id='"room_" . $i++ ."'"></td>";
}
echo "</table></center>";
echo "<script>
";
$i = 1;
while ($row = $result2->fetch_assoc()){
echo "$('#room_" . $i++ . "').html('". $row["roomnumber"] ."');";
}
echo "</script>
";
} else {
echo "0 results";
}
?>

Alex 是正确的,最好获取一个结果,或者组合数组。

但这似乎是不正确的。

echo "</td><td>" . $row["roomnumber"] . "</td></td>" . "</td><td>";

不应该是。

echo "<td>" . $row["roomnumber"] . "</td>" . "<td></td></tr>";

此外,表格单元格=10;不正确的应该是表格单元格="10"。 中心已弃用。