我正在尝试使用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>
这就是我回来的原因
答案 0 :(得分:6)
我看到3条记录。删除:
echo "</table>";
来自while
循环,它会起作用! :)
答案 1 :(得分:2)
您的echo "</table>";
需要超出while
:
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>";
答案 2 :(得分:1)
每件事都很好!!只需
echo "</table>";
从While循环中移除此内容。
<?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>"; Remove This.
}
$result->free(); // free result set
}
?>