试图从BLOB回显一个图像

时间:2015-04-20 10:09:29

标签: php mysql image blob

我有一个页面,用户输入书籍记录的ID,并且应该从数据库中提取用书籍详细信息输入的相应图像(仅图像),该图像存储为BLOB。 - 是的,最好存储图像文件路径 - 我知道这一点,但这并不是我想要在这里实现的目标。

目前,当我按下提交按钮查找用户特定的ID时,它会显示一个带有图像符号但没有图像的页面。

这是我的代码。

require_once __DIR__.'/config.php';
session_start();
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);

$book = $_POST["book_id"];
$stmt = $dbh->prepare("select image from books2 where b_id = $book ");
$stmt->execute();


if ($stmt) {
    if ($row = $dbh->prepare($stmt)) {
       $img = $row["image"];
    }
}

header("Content-type: image/jpeg");

echo "$img";

如何显示图像,我已经阅读了其他问题,但是还没有能够解决这个问题?

3 个答案:

答案 0 :(得分:2)

您有一个SQL注入问题而且您没有使用图像数据获取行:

$book = $_POST["book_id"];
$stmt = $dbh->prepare("select image from books2 where b_id = $book ");
$stmt->execute();


if ($stmt) {
    if ($row = $dbh->prepare($stmt)) {
       $img = $row["image"];
    }
}

应该是这样的:

$stmt = $dbh->prepare("select image from books2 where b_id = ?");
$stmt->execute(array($_POST["book_id"]));

if ($row = $stmt->fetch()) {
   $img = $row["image"];
}

另请注意,如果未找到任何行,您将无法进行任何错误处理。你也应该加上它。

答案 1 :(得分:1)

使用以下方法,而不是像这样添加它更好。

只需将您的代码添加到一个文件中即可调用 display.php

require_once __DIR__.'/config.php';
session_start();
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);

$book = $_GET["book_id"];
$stmt = $dbh->prepare("select image from books2 where b_id = $book ");
$stmt->execute();


if ($stmt) {
    if ($row = $dbh->prepare($stmt)) {
       $img = $row["image"];
    }
}

header("Content-type: image/jpeg");

echo "$img";

然后使用 img 标记,您可以通过将 book_id 作为 url 传递到 src

如下所示

<img src="display.php?book_id=123" alt="your alt title"  />

答案 2 :(得分:1)

这是工作代码,感谢这个问题的帮助: PHP: Retrieve image from MySQL using PDO建议Ryan Vincent

$book = $_GET["book_id"];
$sql = "SELECT image FROM books2 WHERE b_id=:id";
$query = $dbh->prepare($sql);
$query->execute(array(':id' => $book));

$query->bindColumn(1, $image, PDO::PARAM_LOB);
$query->fetch(PDO::FETCH_BOUND);
header("Content-Type: image");
echo $image;