0

I want to make a photo gallery with 3 columns using Bootstrap. My gallery structure should be like this:

<div class="row">
   <div class="col-4" id="box1">
      <img class="img-fluid" src="images/image1.jpg">
      <img class="img-fluid" src="images/image4.jpg">
   </div>
   <div class="col-4" id="box2">
      <img class="img-fluid" src="images/image2.jpg">
      <img class="img-fluid" src="images/image5.jpg">
   </div>
   <div class="col-4" id="box3">
      <img class="img-fluid" src="images/image3.jpg">
      <img class="img-fluid" src="images/image6.jpg">
   </div>
</div>

Currently, I'm fetching the imageURL all in the box1 div. But how can I fetch the images information and organise them in such a way that the 1st image URL value goes as a src in the first div (box1) and the 2nd in the box2 div, 3rd in the box3 div and 4th again in box1 and so on. How can I loop this logic?

<div class="row">
   <?php
      $imageQuery = $mysqli->query("SELECT imageURL FROM images WHERE album = 'UK' ORDER BY date ASC") or die($mysqli->error);
      while ($rowImage = $imageQuery->fetch_array()) { ?>
   <div class="col-4" id="box1">
      <img class="img-fluid" src="<?php echo $rowImage['imageURL']; ?>">
   </div>
   <?php } ?>
</div>
Hijibiji
  • 428
  • 4
  • 20
  • 1
    It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman May 25 '21 at 12:21

1 Answers1

1

You should be able to chunk your array of images into 3 columns each with array_chunk(). Then you can use a normal foreach loop to iterate each one of the 3 columns separately.

<?php
$imageQuery = $mysqli->query("SELECT imageURL FROM images WHERE album = 'UK' ORDER BY date ASC");
$images = $imageQuery->fetch_all(MYSQLI_ASSOC);
$images = array_chunk($images, 3);
?>
<div class="row">
   <div class="col-4" id="box1">
   <?php foreach (array_column($images, 0) as $image): ?>
        <img class="img-fluid" src="<?= $image['imageURL']; ?>">
   <?php endforeach; ?>
   </div>
   <div class="col-4" id="box2">
   <?php foreach (array_column($images, 1) as $image): ?>
        <img class="img-fluid" src="<?= $image['imageURL']; ?>">
   <?php endforeach; ?>
   </div>
   <div class="col-4" id="box3">
   <?php foreach (array_column($images, 2) as $image): ?>
        <img class="img-fluid" src="<?= $image['imageURL']; ?>">
   <?php endforeach; ?>
   </div>
</div>
Dharman
  • 30,962
  • 25
  • 85
  • 135