newbie newbie - 4 months ago 10
PHP Question

Get two adjacent images in a while loop PHP

I have a html code , when i convert into php some issues happended . Actually i need a

foreach
or
while loop
for the below div.

But all images are different (never mind the names of images, it can be any name).

<div class='img'>
<img src='img/1.jpg'>
<img src='img/2.jpg'>
</div>
<div class='img'>
<img src='img/3.jpg'>
<img src='img/4.jpg'>
</div>
//....more divs like this


Here my try

$stmt=$db->query("Select * from photo");
foreach ($stmt as $row)
{

?>
<div class='img'>
<img src='img/<?php echo $row['image']; ?>'>
<img src='img/<?php echo $row['image']; ?>'> // how to get this image diffent from above images
</div>
<?php }


Any experts?

Answer

Try that:

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare("SELECT * FROM photo");
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
?>
<?php $i = 0; ?>
<?php $response = array(); ?>
<?php foreach ($data as $dataIndex => $dataValue): ?>
    <?php if ($i == 1): ?>
        <?php $response[] = '<img src="img' . $dataValue["image"] . '"/>'; ?>
        <?php $response[] = "</div>"; ?>
        <?php $i = 0; ?>
    <?php else: ?>
        <?php $response[] = "<div class='img'>"; ?>
        <?php $response[] = '<img src="img' . $dataValue["image"] . '"/>'; ?>
        <?php $i++; ?>
    <?php endif; ?>
<?php endforeach; ?>
<?php if(count($data)%2): ?>
  <?php $response[] = "</div>"; ?>
<?php endif; ?>
<?php echo implode("", $response); ?>

output:

<div class="img">
  <img src="img1">
  <img src="img2">
</div>

<div class="img">
  <img src="img3">
  <img src="img4">
</div>

<div class="img">
  <img src="img5">
  <img src="img6">
</div>