简体   繁体   中英

Displaying Image from Mysql with PHP

This is what my table looks like in my database. I'm trying to display an image I stored it's a mimetype (longblob) . When I run the code it gives me a small box with a ? , no error just that box. Does anyone know what the error is and how I can fix it?

Display
+-------+------------+----------+
| Index | Display_ID | Picture  |
+-------+------------+----------+
|     1 |         12 | longblob |
+-------+------------+----------+


<?php
    $mysqli=mysqli_connect('localhost','root','','draftdb');


    if (!$mysqli)
        die("Can't connect to MySQL: ".mysqli_connect_error());

    $imageid= 12;

    $stmt = $mysqli->prepare("SELECT PICTURE FROM display WHERE DISPLAY_ID=$imageid"); 
    $stmt->bind_param("i", $imageid);

    $stmt->execute();
    $stmt->store_result();

    $stmt->bind_result($image);
    $stmt->fetch();

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

This:

$stmt = $mysqli->prepare("SELECT PICTURE FROM display WHERE DISPLAY_ID=$imageid");

Should be:

$stmt = $mysqli->prepare('SELECT PICTURE FROM display WHERE DISPLAY_ID=?');

You were directly embedding the variable in the query instead of actually using the bound variables like you intended to.

It's not directly answering this, but typically this isn't how you do this.

Usually you would store the path for the image in the database (maybe as a varchar field) then just load the image as per usual. This has benefits that it's easy, keeps the DB small and more easily versioned, the normal caching rules apply to the images etc.

The downside is that anyone can view the images, which may or may not cause an issue.

If you need to go down the route you have started, start by commenting out header("Content-Type: image/jpeg"); and see what the PHP errors are. This may help.

It is neccessary to specify a content-length header too:

header("Content-Length: ".strlen($image));
header("Content-Type: image/jpeg");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM