Show image from blob mysql
Hi I have a table of images in my database. They are saved as blobs along with details such as the type and name of the image.
I have an image problem, all I get is a white box with a red cross. the code:
<?php
include '../connection.php';
$ID = $_GET['id'];
$query = "SELECT * FROM `images` WHERE `image_id` = '$ID'";
$result=mysql_query($query);
$row = mysql_fetch_array($result);
$image = $row['image'];
$image_type= $row['image_type'];
header("Content-type: $image_type");
print $image;
exit;
?>
thanks
a source to share
Ok, here's the short answer.
<?php
include '../connection.php';
$id = (int)$_GET['id'];
$query = "SELECT * FROM `images` WHERE `image_id` = '$id'";
$result=mysql_query($query);
$row = mysql_fetch_array($result);
$image = $row['image'];
$image_type= $row['image_type'];
$size = $row['image_size'];
//alternative
/* list($image, $image_type, $size) = array(
$row['image'],
$row['image_type'],
$row['image_size']
);
*/
$ext = explode('/', $image_type);
$name = $id . '.' . $ext[1];
header("Content-type: $image_type");
header("Content-length: $size");
header("Content-Disposition: attachment; filename=$name");
print $image;
exit;
Check your blobtype as least MEDIUMBLOB capable of storing data up to 16M
a source to share
A few things to try
-
maybe something is not working and it is returning an error message in html instead of the expected image
-
is the content_type stored correctly in the database, or you just keep the image file extension
the content type should look something like this.
image/gif image/jpeg
a source to share
You said in a comment that the table originally said "[BLOB - 64.0 KiB]", but you changed it to "MEDIUMBLOB". This will expand the size you can keep, but all of your existing data will still be truncated to 64KiB.
Make sure the field type you are using is large enough to hold the data you want to store (16MB in MEDIUMBLOB or ~ 4gb in LONGBLOB, I'm sure), then re-insert all your data.
Apart from the security issues mentioned, I don't understand why the code shouldn't work any differently than a database problem.
a source to share