简体   繁体   English

使用PHP从Mysql显示图像

[英]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) . 我正在尝试显示存储的图像是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. 通常,您会将图像的路径存储在数据库中(也许作为varchar字段),然后照常加载图像。 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"); 如果您需要沿着开始的路线走,请首先注释掉header("Content-Type: image/jpeg"); and see what the PHP errors are. 并查看什么是PHP错误。 This may help. 这可能会有所帮助。

It is neccessary to specify a content-length header too: 也必须指定一个内容长度标头:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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