表
id m_id image
1 1 img1.jpg
2 2 img2.jpg
3 1 img11.jpg
4 2 img22.jpg
5 1 img111.jpg
........ etc
我需要的是 - 通过m_id从表组中只获取2行,如下所示
//here getting images where m_id=1 and it is not more than 2
<section class='test'>
<div class="n-2">
<img src='img1.jpg'>
</div>
<div class="n-2">
<img src='img11.jpg'>
</div>
</section>
//next fetching images with m_id=2
<section class='test'>
<div class="n-2">
<img src='img2.jpg'>
</div>
<div class="n-2">
<img src='img22.jpg'>
</div>
</section>
......
我尝试的是
<?php
$query=$db->query("Select * from gallery order by m_id asc");
$result = $query->fetchAll(\PDO::FETCH_ASSOC);
for ($i=0; $i < count($result); $i+=2) {
?>
<section class='test'>
<div class="n-2">
<img src='<?php $result[$i]['image']; ?>'>
</div>
<div class="n-2">
<img src='<?php $result[$i+1]['image']; ?>'>
</div>
</section>
<?php
}
?>
但是我将所有字段都显示在显示的section class'test'
中,如何获得显示的部分类中仅有的2行。
有专家吗?
答案 0 :(得分:0)
您好这个查询只能获得两条记录 你应该阅读w3schools.com
中的MySql教程Select * from gallery order by m_id asc LIMIT 2
更新1:这将有希望在你的情况下。
$query = $db->query("Select * from gallery order by m_id asc");
$items = $query->fetchAll(\PDO::FETCH_ASSOC);
$result = [];
$temp = [];
foreach ($items as $item) {
$m_id = $item['m_id'];
if (!isset($temp[$m_id]) || count($temp[$m_id]) < 2) {
$temp[$m_id][] = $item['image'];
$result = $item['image'];
}
}
for ($i = 0; $i < count($result); $i += 2) {
?>
<section class='test'>
<div class="n-2">
<img src='<?php $result[$i]['image']; ?>'>
</div>
<div class="n-2">
<img src='<?php $result[$i + 1]['image']; ?>'>
</div>
</section>
<?php
}