从PHP中具有相同列值的表中获取2行

问题描述 投票:1回答:1

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行。

有专家吗?

php mysql group-by limit
1个回答
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
}
© www.soinside.com 2019 - 2024. All rights reserved.