从SQL数据库中检索varbinary图像

时间:2017-10-15 02:56:28

标签: php mysql sql image mysqli

我创建了一个非常简单的PHP和SQL博客。我在数据库中有以下字段:post_title,post_content,post_category,post_date,post_image,user_name。 post_image字段是VARBINARY(255)。我可以在数据库中成功上传文件,但是如何在之后检索并显示它?这是显示博客的代码。我想在h2标签上方显示图片:

<?php
while($column = mysqli_fetch_assoc($post)){
?>
<h2 class="post-title"><?php echo $column["post_title"]?></h2>
<div class="view-post-content"><?php echo $column["post_content"]?></div>
<p class="category">Category: <?php echo $column["post_category"]?></p>
<p>This post was written <?php echo $column["post_date"]?> by <?php echo $column["user_name"]?>.</p>
<a href="edit_post.php?id=<?php echo $column['post_id'] ?>">Edit</a> | <a href="delete_post.php?id=<?php echo $column['post_id'] ?>" onclick="return confirm('Are you sure?')">Delete</a>
<hr>
<?php
}
?>

1 个答案:

答案 0 :(得分:0)

两种方式:

1-仅创建另一个php以加载varbinary:

例如load_img.php:

<?php

...
if(isset($_REQUEST['id'])) {
$sql = "SELECT post_mime, post_image FROM post WHERE post_id=" . $_GET['id'];
$result = mysqli_query("$sql");
$row = mysqli_fetch_array($result);
header("Content-type: " . $row["mime"]);
echo $row["img"];
}
mysql_close($conn);

在H2之上:

echo '<img src="load_img.php?id='.$column['post_id'].'" />';

2-或使用base64 css:

echo '<img src="data:image/jpeg;base64,'.base64_encode( $column['post_image'] ).'"/>';

我会建议一个新字段来存储 mimetype (jpg,png,gif等...)