Samuel Holland
Samuel Holland

Reputation: 81

How to take an image from My SQL database and add it to a .html page

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?

Upvotes: 0

Views: 891

Answers (1)

dearsina
dearsina

Reputation: 5192

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.

Upvotes: 1

Related Questions