2 回答
TA贡献1906条经验 获得超10个赞
关于您的代码风格的两个方面的评论:
1) 尽量避免使用echo静态 HTML 内容 - 禁用 PHP。
2) 尝试将您的数据库逻辑与 HTML 分开 - 代码会更干净。
$rows = [];
if ($result = mysqli_query($link, "SELECT * FROM factory ORDER BY Fac_ID ASC"))
{
while ($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
}
$rows_chunked = array_chunk($rows, 3);
?>
<table class="table table-bordered" bgcolor="#ffffff" width="50%">
<?php
foreach ($rows_chunked as $rows)
{
?><tr><?php
foreach ($rows as $row)
{
?><td><?php echo $row['Fac_ID'] ?></td><?php
}
echo str_repeat('<td></td>', 3 - count($rows));
?></tr><?php
}
?>
</table>
TA贡献1829条经验 获得超7个赞
如果您的数据不会自然地填满表格的所有单元格,您应该质疑表格是否是显示它的正确方式。
CSS 可以稍微调整一下就可以显示出来,而不必担心将结果拆分成行;运行纯 html 表示的示例:
.lined {
border-top-style: dashed;
border-bottom-style: dashed;
margin-top: -3px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-sm-3">Page Column 1</div>
<div class="col-sm-3">Page Column 2</div>
<div class="col-sm-3">Page Column 3</div>
<div class="col-sm-3">Page Column 4</div>
</div>
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-3">
<div class="row">
<div class="col-sm-4 lined">1</div>
<div class="col-sm-4 lined">2</div>
<div class="col-sm-4 lined">3</div>
<div class="col-sm-4 lined">4</div>
<div class="col-sm-4 lined">5</div>
<div class="col-sm-4 lined">6</div>
<div class="col-sm-4 lined">7</div>
<div class="col-sm-4 lined">8</div>
</div>
</div>
<div class="col-sm-3"></div>
<div class="col-sm-3"></div>
</div>
您需要做的就是将您的数据合并到 html 中:
<?php
$sql = "SELECT * FROM factory ORDER BY Fac_ID ASC";
if(!$result = mysqli_query($link, $sql)){ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); }
$rows = array();
while($row = mysqli_fetch_array($result)){
$rows[] = $row;
}
mysqli_free_result($result);
?>
<div class="row">
<div class="col-sm-3">Page Column 1</div>
<div class="col-sm-3">Page Column 2</div>
<div class="col-sm-3">Page Column 3</div>
<div class="col-sm-3">Page Column 4</div>
</div>
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-3">
<div class="row">
<?php foreach($rows as $r): ?>
<div class="col-sm-4 lined"><?= $r['Fac_ID'] ?></div>
<?php endforeach; ?>
<?php if(sizeof($rows) == 0): ?>
<p class='lead'><em>No records were found.</em></p>
<?php endif; ?>
</div>
</div>
<div class="col-sm-3"></div>
<div class="col-sm-3"></div>
</div>
- 2 回答
- 0 关注
- 149 浏览
添加回答
举报