我正在尝试使用 while()
循环从名为 orders 的表中返回所有数据,并将它们打印在 HTML 表中。
我尝试了两种遍历数据的方法。
while($row = mysqli_fetch_assoc($result))
while($row = $result->fetch_assoc())
这两种方式都只将第一行添加到我的 HTML 表中,而只将任何其他行回显到页面。
代码如下:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>FORM SUCCESSFULLY SENT</h1>
<p>Here are the order details</p>
<?php
$servername = xxxx;
$username = xxxx;
$password = xxxx;
$databasename = xxxx;
$conn = new mysqli($servername, $username, $password, $databasename); // Create connection
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error); // Check connection
$sql_query = "SELECT * FROM orders";
$result = mysqli_query($conn,$sql_query);
?>
<table border="3" style= "background-color: #84ed86; color: #761a9b; margin: 5 auto;" >
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Start City</th>
<th>End City</th>
<th>Tracking Number</th>
</tr>
</thead>
<tbody>
<?php
if (!$result) throw new Exception('Database error: ' . mysql_error());
else
{
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['client_name']."</td>";
echo "<td>".$row['client_surname']."</td>";
echo "<td>".$row['client_start_city']."</td>";
echo "<td>".$row['client_end_city']."</td>";
echo "<td>".$row['order_tracking_number']."</td>";
echo "</tr>";
echo "</table>";
}
$result->free(); // free result set
}
?>
</tbody>
</table>
<?php
$conn->close();
?>
</body>
</html>
这就是我得到的结果
最佳答案
我看到 3 条记录。删除:
echo "</table>";
从 while
循环开始,它会起作用! :)
关于php - 我只得到我 table 的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45234030/