在查询数据库时,如何对 HTML 表格列的数量施加限制。
例如,我有一个包含以下值的 MySQL 表:
myTable:
id color
1 red
2 blue
3 green
4 pink
5 purple
当我运行查询时,不是显示传统表行中的所有行,例如
<table>
<?php
while {
echo "<tr><td>$row['color']</td></tr>;
}
?>
</table>
相反,我想强制执行一些操作,每三个 td 创建一个新的 tr。
例如,它会输出如下内容:
<table>
<tr>
<td>red</td>
<td>blue</td>
<td>green</td>
</tr> <-- Notice how after 3 columns, a new table row is created.
<tr>
<td>pink</td>
<td>purple</td>
</tr>
</table>
有什么办法可以实现这个目标吗?
最佳答案
为了实现此目的,您可以结合使用计数器和 modulus (%
)运算符:
<table>
<?php
$count = 0;
while($row = mysql_fetch_array($results)) {
$outputTr = ($count % 3) == 0;
if($outputTr) echo '<tr>';
echo '<td>' . $row['color'] . '</td>';
if($outputTr) echo '</tr>';
$count++;
}
?>
</table>
关于PHP/MySQL 在 TD 中输出数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1197887/