我正在浏览各种网站,了解如何跳过mysql fetch assoc
和php do while
生成的一行,但找不到这个解决方案。我正在从数据库生成html表。从下面的代码中,我得到了一个额外的空行。我的数据库表上有三个数据。在这里,这段代码生成了五行,而我期望生成四行。
我的完整代码如下:
<?php
$sql = "SELECT * from $table where Year='2013'";
$result = mysql_query($sql);
if(!$result) {
die(mysql_error()); // TODO: better error handling
}
?>
<table><tr>
<th>Name</Name>
<th>Date</th>
</tr>
<?php do { ?>
<tr>
<td><?php echo $row['Name'];?></td>
<td><?php $ndt = strtotime($row['date']); echo date('d-M-Y', $ndt); ?></td>
<?php } while ($row= mysql_fetch_assoc($result)); ?>
</tr>
</table>
切换到while循环。
<?php while ($row= mysql_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['Name'];?></td>
<td><?php $ndt = strtotime($row['date']); echo date('d-M-Y', $ndt); ?></td>
<?php } ?>
do/while循环的第一次$row没有被填充,因此您得到了一个空行。
为什么不简单地使用while循环?
<?php
$sql = "SELECT * from $table where Year='2013'";
$result = mysql_query($sql);
if(!$result) {
die(mysql_error()); // TODO: better error handling
}
?>
<table><tr>
<th>Name</Name>
<th>Date</th>
</tr>
<?php while ($row= mysql_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['Name'];?></td>
<td><?php $ndt = strtotime($row['date']); echo date('d-M-Y', $ndt); ?></td>
<?php } ?>
</tr>
</table>
请更改以下代码:
<table>
<tr>
<th>Name</th>
<th>Date</th>
</tr>
<?php while ($row= mysql_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row['Name'];?></td>
<td><?php $ndt = strtotime($row['date']); echo date('d-M-Y', $ndt); ?></td>
<?php } ; ?>
</tr>
</table>