我正在制作一个后端系统,索引页面显示的产品应该遵循网格系统。例如,我有来自 MySql 数据库的 8 个产品。我想将它们分成 2 行,每行 4 个产品。所以我的 PHP 代码如下所示:
<div class="row">
<?php
$result = mysqli_query($conn, "SELECT * FROM products");
while ($row = mysqli_fetch_array($result)) {
?>
<div class="col-dsk-4"><?php echo $row["name"]; ?></div>
<?php
}
?>
</div>
正如您在代码中看到的,我希望在回显 4 次(4 次 <div class="col-dsk-4">
)后, while 循环退出,然后继续新的 <div class="row">
。直到循环遍历MySql Table中的所有元素。
我的解决方案是否正确?如果是这样,请帮助我,否则,请告诉我你的解决方案。
最佳答案
您可以尝试下面的代码。
我正在做的不是使用 while
我已将其切换为 foreach
遍历数组。
我正在使用count
指示何时 <div class="row">
应该添加。
在第一项和每第四项上,应该添加一个新行。
我还更新了调用<?php ?>
的方式所以更容易/更清晰地阅读。
如果您有任何疑问,请告诉我:
<?php $result = mysqli_query($conn, "SELECT * FROM products"); ?>
<?php $rows = mysqli_fetch_array($result); ?>
<!-- Use count to decide when to put a new div with class 'row' -->
<?php $count = 1; ?>
<?php foreach ($rows as $key => $row) { ?>
<!-- Create a new div with class 'row' on the first item + everytime theres a 4th one -->
<?php if ($count == 1 || ($count % 4 == 0)) { ?>
<div class="row">
<?php } ?>
<div class="col-dsk-4">
<?php echo $row["name"]; ?>
</div>
<!-- Close div with class 'row' everytime theres a 4th one -->
<?php if ($count == 1 || ($count % 4 == 0)) { ?>
</div>
<?php } ?>
<!-- Increment the count -->
<?php $count++; ?>
<?php } ?>
关于php - 如何在MySQL数据库中获取4行后回显特定内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47065725/