我正在浏览各种网站,了解如何跳过mysql fetch assoc和php do while生成的额外一行,但找不到这个解决方案。我正在从数据库中生成html表。从下面的代码中,我得到了一个额外的空行。我的数据库表中有三个数据。在这里,这段代码生成了5行代码,而我期望生成4行。
我的完整代码如下:
<?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>发布于 2013-07-23 13:47:29
切换到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没有被填充,因此您会得到一个空行。
发布于 2013-07-23 13:48:01
为什么不简单地使用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>发布于 2013-07-23 13:48:35
请更改以下代码:
<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>https://stackoverflow.com/questions/17802275
复制相似问题