我试图遍历我数据库中的一个表并在表中显示所有详细信息。首先,它应该遍历我的主表“TBook”,并获取“日期”、“期间”、roomID 和“teacherinitials”。然后,使用 roomID,它应该在我的另一个表“房间”中查找,以获取“房间”名称和“描述”。之后它应该显示“日期”、“期间”、“房间”和“描述”以及“教师首字母”。
这是我的代码:
<?php
// Create connection
$con=mysqli_connect("host","user","pass","database");
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Get number of rows
$sql="SELECT * FROM TBook";
$result=mysqli_query($con, $sql);
$rowcount=mysqli_num_rows($result);
$sql2="SELECT room, description FROM Rooms WHERE roomID = $roomID";
$res=mysqli_query($con,$sql2);
//Start table
echo "<table>";
echo "<tr><th>Date</th><th>Period</th><th>Room</th><th>Teacher Initials</th></tr>";
// Loop through database
while ($row = $result->fetch_assoc()) {
$row = mysql_fetch_array($result);
$date = $row['date'];
$period = $row['period'];
$roomID = $row['roomID'];
$teacherinitials = $row['teacherinitials'];
while ($row2 = $res->fetch_assoc()) {
$room = $row2['room'];
$description = $row2['description'];
}
// Show entries
echo "<tr>
<td>".$date."</td>
<td>".$period."</td>
<td>".$room." (".$description.")</td>
<td>".$teacherinitials."</td>
</tr>";
}
echo "</table>";
?>
但是,我收到一条错误消息“ fatal error :在第 56 行的/home/user/public_html/my_bookings-results.php 中的非对象上调用成员函数 fetch_assoc()”。第 56 行是这一行:
while ($row2 = $res->fetch_assoc()) {
它确实在其下方显示了表格标题,但没有其他内容。出了什么问题?
最佳答案
先把while循环改成
while ($row = mysql_fetch_array($result))
在 while 循环后删除下一行
$row = mysql_fetch_array($result);
改变:
while ($row2 = $res->fetch_assoc()) {
到
while ($row2 = $res->fetch_array($res)) {
关于php - 使用 PHP 循环遍历数据库并填充 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21186886/