问题
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:
http://i.imgur.com/NQOPSAf.png
回答1:
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));
Edit
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'])
回答2:
Try to replace
header("content-type: image/jpeg");
with
header("content-type: image/png");
回答3:
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.
- if you are use PHP >= 5.4, $query->execute([":id" => $id]);can be used instead of$query->execute(array(":id" => $id));
来源:https://stackoverflow.com/questions/24632118/php-image-blob-wont-show