Home » Php » PHP display image BLOB from MySQL

PHP display image BLOB from MySQL

Posted by: admin April 23, 2020 Leave a comment


I’m attempting to display an image stored in the BLOB column in the database;

I fetch the data from the database with a SELECT perform no transformations on the data and display it with the following (from a script whose only output is the following):

header("Content-Type: image/jpeg");
echo $image;

Please note chrome is displaying the content size as the correct size for the image as well as the correct mime type (image/jpeg). nothing is echoing out before the header and ive checked the blob in the database is correct. There is also no trailing whitespace before or after the <?php ?> tags.

chrome/IE displays an image icon but not the image itself. any ideas?

EDIT: image is got the from the database as such:

$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$row = $sth->fetch();
$image = $row['image'];

var_dump($image) gives:

string 'ÿØÿà�JFIF��x�x��ÿá�ZExif��MM�*�����������J��������Q�������Q������tQ������t�����† ��±ÿÛ�C�       

%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³    ´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ��������'... (length=60766)
How to&Answers:

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.



This is what I use to display images from blob:

echo '<img src="data:image/jpeg;base64,'.base64_encode($image->load()) .'" />';


Since I have to store various types of content in my blob field/column, I am suppose to update my code like this:

echo "data: $mime" $result['$data']";

mime can be an image of any kind, text, word document, text document, PDF document, etc… content datatype is blob in database.