我的任务有问题,我想用3列水平显示我的记录
不幸的是,我的显示器变成了垂直的。
该任务要求我们使用模数(%(运算符来显示记录。记录存储在数据库中(id、标题、图片、类别、作者(。数据库中存储了11本书。这是我的PHP代码:
<?php
include_once('config.php');
$result = mysqli_query($mysqli, "SELECT * FROM books ORDER BY id ASC");
?>
<style>
img {
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
width: 200px;
}
.p2 {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
padding-left: 10px;
}
.p3 {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
padding-left: 10px;
color: blue;
}
</style>
<div class="container">
<center>
<h1>Koleksi Buku Peribadi</h1>
<table>
<?php
$x=11;
$y=3;
$i=$x % $y;
while($i && $book = mysqli_fetch_array($result)) {
?>
<tr>
<td>
<img src="Gambar-buku/<?php echo $book['picture'];?>">
<p class='p2'>Penulis:<span class='p3'> <?php echo $book['author'];?> </span>
<br> <i><?php echo $book['category'];?></i>
</p>
<center><button type="button">Details</button> </center>
</td>
</tr>
<?php
$i++; }
?>
</table>
</center>
</div>
当您需要将项目平均划分为多个类别时,模数非常有用。
正式名称:index_of_category = index_of_item % number_of_categories
实际上:在您的案例中,您有3个类别(列(。对于索引为i
的项,可以找到其索引为i % 3
的列的索引。
为了使表格布局工作,您需要:
- 为索引为0的列中的每个项目打印
tr
打开标记 - 为索引为2的列中的每个项目打印
tr
结束标记
在我的示例中,您可以通过修改$numberOfColumns
变量来轻松地更改列数。
<div class="container">
<center>
<h1>Koleksi Buku Peribadi</h1>
<table>
<?php
$numberOfColumns = 3;
for ($i = 0; (($book = mysqli_fetch_array($result)) !== null); $i++) {
$printRowOpeningTag = $i % $numberOfColumns === 0;
$printRowClosingTag = $i % $numberOfColumns === $numberOfColumns - 1;
if ($printRowOpeningTag) {?>
<tr>
<?php } ?>
<td><img src="Gambar-buku/<?php echo $book['picture'];?>">
<p class='p2'>Penulis:<span class='p3'> <?php echo $book['author'];?> </span>
<br> <i><?php echo $book['category'];?> </i>
</p>
<center><button type="button">Details</button> </center>
</td>
<?php if ($printRowClosingTag) { ?>
</tr>
<?php } ?>
<?php
} ?>
</table>
</center>
</div>