Skip to content
Advertisement

How to echo multiple images using an Array

Using this code:

<?php
$stmt = $pdo->prepare("SELECT pdimg1 FROM products WHERE pdcat LIKE 'fashion%'");
$stmt->execute();
$rows = $stmt->fetchAll();
$img1 = '';
foreach ($rows as $row) {
    $Rpdimg1 = $row['pdimg1'];
    $img1 .= $Rpdimg1;
}

UPDATED TO INCLUDE BELOW:
$stmt = $pdo->prepare("SELECT * FROM products WHERE pdcat LIKE 'collectibles%'");
$stmt->execute();
$rows = $stmt->fetchAll();
$img2 = '';
foreach ($rows as $row) {
    $Rpdimg2 = htmlspecialchars($row['pdimg1']);
    $img2 .= $Rpdimg2;
}

$cats = array(
            array(
                "title" => "FASHION",
                "img" => $img1
            ),
            array(
                "title" => "COLLECTIBLES & ART",
                "img" => $img2,
            )
        );

foreach ($cats as $cat): ?>
    <?php echo $cat["title"]; ?>
    <img src="images/<?php echo $cat["img"]; ?>">
<?php endforeach; ?>

I get this result displayed in Inspector Tools on Firefox:

<img src="images/shirt.jpgpants.jpg">

[But on the webpage, this displays as a broken image.]

But what I want is this result:

<img src="images/shirt.jpg">
<img src="images/pants.jpg">

[However, I would like the above results displayed as IMAGES, not as html text.]

Those two images are values echoed from my database. They are from my products table:

pdid | pdimg1
-----------------
  1  | shirt.jpg
  2  | pants.jpg

So basically

1) I’m selecting rows from my database table products

2) I’m inserting them as variables into an array (which is used for other purposes)

3) I’m using a foreach loop to echo out those variables from that array

4) Now the problem lies in that those IMAGE variables bunch together as a SINGLE WORD (shirt.jpgpants.jpg) instead of as separated values, and do not get encased in their OWN img tags, but are bunched together under the same img tag.

5) So I demonstrated above in bold text the result that I wanted. How would I achieve this? Thank you

Advertisement

Answer

you need to do array assignment inside loop, and bit reduced code like below:

<?php
$stmt = $pdo->prepare("SELECT pdimg1 FROM products WHERE pdcat LIKE 'fashion%'");
$stmt->execute();
$rows = $stmt->fetchAll();

$cats = array();
foreach ($rows as $row) {
    $cats[] = array(
    "title" => $row['title'];
    "img" => $row['pdimg1']; 
   ); // you can add as many column as you get from query
}

foreach ($cats as $cat): ?>
    <?php echo $cat["title"]; ?>
   <img src="images/<?php echo $cat["img"]; ?>">
<?php endforeach; ?>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement