我正在使用数据库开发照片库。在一切重置之前,每行显示 3 个图像。它将位于 <img>/<img>/<img>/<div>
中格式。
因此,当查看源代码时,您会得到:
<img src="1" alt="">
<img src="2" alt="">
<img src="3" alt="">
<div class="clear-both"></div>
并且它会对数据库中的每一行不断重复此操作。所以 9 张图像将是:
<img src="1" alt="">
<img src="2" alt="">
<img src="3" alt="">
<div class="clear-both"></div>
<img src="4" alt="">
<img src="5" alt="">
<img src="6" alt="">
<div class="clear-both"></div>
<img src="7" alt="">
<img src="8" alt="">
<img src="9" alt="">
<div class="clear-both"></div>
我想我可以使用 while
来处理这个问题。但我不知道要添加什么SQL或PHP语句。我考虑过使用WHERE
, GROUP BY
和COUNT
,但这些都不起作用。
如果可能的话,我还希望它能够处理仅包含 1 个和 2 个图像的行。意思是如果表中有4行,那么它会显示:
<img src="1" alt="">
<img src="2" alt="">
<img src="3" alt="">
<div class="clear-both"></div>
<img src="4" alt="">
<div class="clear-both"></div>
如果有 8 个,则会显示:
<img src="1" alt="">
<img src="2" alt="">
<img src="3" alt="">
<div class="clear-both"></div>
<img src="4" alt="">
<img src="5" alt="">
<img src="6" alt="">
<div class="clear-both"></div>
<img src="7" alt="">
<img src="8" alt="">
<div class="clear-both"></div>
感谢您的帮助。
PHP
$Database4 = new mysqli("localhost", "user", "pass", "Photography");
$Photos = $Database4 -> query("SELECT *
FROM `Year2016`
-- ORDER BY DateTaken
;");
while ($DataRows = $Photos -> fetch_array()) {
echo '<img src="photography/small/' . $DataRows["file"] . '" alt="">' . "\n";
}
echo '<div class="clear-both"></div>' . "\n";
SQL
CREATE TABLE `Year2016`(
`file` text COLLATE utf8_bin NOT NULL,
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8
COLLATE = utf8_bin;
INSERT INTO `Year2016`(`file`)
VALUES
('red-1.png'),
('red-2.png'),
('red-3.png'),
('red-4.png'),
('red-5.png'),
('red-6.png');
最佳答案
这很简单:
$i = 1; // special counter
while ($DataRows = $Photos -> fetch_array()) {
echo '<img src="photography/small/' . $DataRows["file"] . '" alt="">' . "\n";
if ($i % 3 == 0) {
echo '<div class="clear-both"></div>';
}
$i++;
}
// the last one if last `$i` value is not divided by 3
if ($i % 3 != 1) {
echo '<div class="clear-both"></div>';
}
关于php - MySQL 和 PHP : querying 3 rows at a time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38798397/