0

I have some images in a database which I would like to add to a html page This is my current code

<div class = "gridrow">
    <?php
        foreach (range(1, 4) as $value) {
        $result = $conn->query("select * from products where product_ID = '".$value."'");
        $row = $result->fetch_array();
        $name_p1 = $row['product'];
        $price_p1 = $row['price'];
        $image = "<img src='{$row['image']}'>";
        echo "<div class = 'productwindow' >";
            echo "<div class = 'productimage'><".$image."></div>";
            echo "<div class = 'productvar'><p>".$name_p1."</p></div>";
            echo "<div class = 'productvar'><p>$".$price_p1."</p></div>";
        echo "</div>";
        }
    ?>
</div>

This is what the page looks like

These are the errors I get

How can I make these images show correctly?

  • For starters, you'll need to run a PHP script on a `.php` page rather than a `.html` page (unless you're explicitly enabling that functionality in `.html` through Apache2's `@mime.conf`)... – Obsidian Age Aug 12 '21 at 03:06
  • 1
    First fix your SQL injection. Second, you probably shouldn't be storing images in the database, its not what database are good at. If you insist on doing so, use ``. – Alex Barker Aug 12 '21 at 03:49

1 Answers1

1

You're storing image data in the database, while the img src tag wants image URLs, that's why it's getting confused and you're getting errors.

The quick way around it is to convert the image data to base64 and pipe it in the src tag like so:

$image = '<img src="data:image/png;base64,'.base64_encode($row['image']).'">';

This is at best a hack, and not a great idea for a host of reasons, it also assumes all your images are PNG.

dearsina
  • 4,774
  • 2
  • 28
  • 34