Taha Kirmani
Taha Kirmani

Reputation: 1274

How to view get image back from MySQL database

I have uploaded an Image in my database. The datatype is BLOB. Now I want to view this image in my browser. I have written the following code but its not generating the image. Kindly check it.

Thanks

<?php

    include 'connect.php';
    //$id= $_GET['product_id'];

    $query_images = "SELECT image FROM product_images WHERE product_id=121";

    if (!$query_images_result = mysql_query($query_images))
    {
        echo mysql_error();
    }
    else
    {

         $fetch_images = mysql_fetch_array($query_images_result);

         $print_images = $fetch_images['image'];

         header('Content-type:image/jpeg');

         echo $print_images;
    }

?>

File 2

<body>

<img src='single_product_image_show.php' alt="image" />

</body>

Upvotes: 0

Views: 457

Answers (2)

srakl
srakl

Reputation: 2619

maybe something like this? You might wanna use base64 encoding to build in the image

FYI: NOT TESTED.

$sql = "SELECT `image` FROM `product_images` WHERE `product_id`=121 LIMIT 1";

$query_images_result = mysql_query($sql);

    if (!$query_images_result)
    {
        echo mysql_error();
    }
    else
    {

       list($print_images) = mysql_fetch_array($query_images_result);

       $base64source = "data:image/jpeg;base64," . base64_encode($print_images);
       echo '<img src="'.$base64source.'" alt="" />';
    }

Upvotes: 1

K&#225;roly Nagy
K&#225;roly Nagy

Reputation: 1754

There are multiple possible reasons why this could happen. First try your script directly without "header('Content-type:image/jpeg');" so you can see what it actually returns. Like http://[youhostname]/single_product_image_show.php I assume you will see some errors.

Some best practices to serve images from php:

  • If you can remove the end php tag (?>). You don't actually need it and you can avoid issues when you have whitespace character after the close tag which will be written to the response and so results as a corrupt image.
  • You should specify the Content-Length header as well. It's not mandatory but the browser will know how big the file it has to download.
  • Specify some cache control headers (https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) so browsers can cache your image so it won't result a full page load and mysql query every time the image appears on the site.
  • You can store ETag and/or Last-modified in the database which you can retrieve and put in the headers.

Upvotes: 0

Related Questions