【发布时间】:2010-02-13 21:20:06
【问题描述】:
我知道如何在 html 表上打印数据库中的数据,但我有一项任务我无法理解,而且我做不到。 我在数据库中有一个表,当我选择这些数据时,我希望它们显示在 html 表上,但类似这样:
【问题讨论】:
我知道如何在 html 表上打印数据库中的数据,但我有一项任务我无法理解,而且我做不到。 我在数据库中有一个表,当我选择这些数据时,我希望它们显示在 html 表上,但类似这样:
【问题讨论】:
要实现这样的表格布局,您只需要调整表格行末尾的位置即可。
<table>
<tr>
<?php
$count = 0;
while($row = mysql_fetch_assoc($result)) :
$count++;
?>
<td><?php echo $row['value'] ?></td>
<?php if($count % 2 == 0 || $count == mysql_num_rows($res)) : ?>
</tr>
<?php if($count != mysql_num_rows($result)) : ?>
<tr>
<?php endif; ?>
<?php endif; ?>
<?php endwhile; ?>
</table>
上面的操作是使用模运算符(%,计算除法的余数)来打印一个结束和开始的行标签,只要我们得到一个偶数的结果。
此外,如果您想将表格布局更改为 3 或 4 列宽,您只需更改应用于模数的数字:
$count % 3 == 0 //3 columns
$count % 4 == 0 //4 columns, etc
【讨论】:
<table>
<?php while (TRUE) { ?>
<?php
// Make an array of n rows. Trailing items may be FALSE if there
// are not enough rows to fill the table row.
//
$rows= array();
for ($i= 0; $i<n; $i++)
$rows[$i]= mysql_fetch_assoc($result);
if (!$row[0])
break;
?>
<tr>
<?php foreach ($rows as $row) { ?>
<td>
<?php if ($row) { ?>
Value: <?php echo(htmlspecialchars($row['value']); ?>
<?php } ?>
</td>
<?php } ?>
</tr>
<?php } ?>
</table>
【讨论】:
echos 更易于维护。