Reputation: 23
So I am trying to show an image from my mysql database. The image is saved as a blob format. I made seperate php file for fetching the image. I then call this file from where I want to show the image like so:
<img src="image.php?id=3" />
This is the file that fetches the image:
<?php
require 'scripts/connect.php';
if(isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$q = $db->prepare("SELECT image FROM products WHERE id = '$id'");
$q->execute();
$data = $q->fetch();
header("content-type: image/jpeg");
echo $data["image"];
}
?>
But when I try and run this code no image shows up. Instead I get this annoying broken link image thing:
https://i.sstatic.net/LGGTF.png
Upvotes: 0
Views: 1335
Reputation: 29912
Your code doesn't do what you expect.
Try to change
$q = $db->prepare("SELECT image FROM products WHERE id = '$id'");
in - if id
field is numeric one; if isn't, add single quote -
$q = $db->prepare("SELECT image FROM products WHERE id = $id");
Your example didn't work as you were passing to query $id
placeholder and not his value (you dind't concatenated it)
Of course with that method you're not save by SQL Injection at all, so you should use pepared statement that way
$q = $db->prepare("SELECT image FROM products WHERE id = :id");
$q->execute(Array(":id" => $id));
As OP told me that $data['image']; is a bitstream, I will suggest to use something like:
echo '<img src="data:image/jpg;base64,'. base64_encode($data['image']). '" alt='imagename'>;
or if your echo goes directly into src
attribute:
echo 'data:image/jpg;base64,'. base64_encode($data['image'])
Upvotes: 1
Reputation: 4037
Try,
$query = $db->prepare("SELECT image FROM products WHERE id = :id");
$query->execute(array(":id" => $id));
$data = $q->fetch();
For serving the image, use
$mime = pathinfo($data['image'], PATHINFO_EXTENSION);
header('Content-Type: '.$mime);
ob_clean();
flush();
readfile($data['image']);
Note:
readfile()
needs the image path to where the images are stored.$query->execute([":id" => $id]);
can be used instead of
$query->execute(array(":id" => $id));
Upvotes: 0
Reputation: 1795
Try to replace
header("content-type: image/jpeg");
with
header("content-type: image/png");
Upvotes: 0