简体   繁体   English

使用 mysqli php 7 从数据库中检索图像

[英]retrieve image from database using mysqli php 7

I am trying to retrieve a png image file from the database我正在尝试从数据库中检索一个 png 图像文件

Here is the call from within the <img> tag inside body:这是来自 body 内<img>标签内的调用:

<img src="..\BankLogin\man.php?id=2" style="width:128px;height:150px">

Here's the man.php file:这是man.php文件:

<?php
   $link = mysqli_connect("localhost","root","","images");
   $imgId = $_GET['id'];
   if (!empty($imgId)) {
   $sqliCommand = "SELECT image FROM images WHERE id = $imgId";
   $result = mysqli_query($sqliCommand,$link);
   $row = mysqli_fetch_assoc($result);
   mysqli_close($link);   
   header("Content-type: image/png");
   echo $row['image'];
  }
?>

On running the code i just get an image frame with an 'unloaded image'(am i saying it correct?).I am pretty sure something is wrong in the man.php file, maybe in echo $row['image'].在运行代码时,我只得到一个带有“未加载图像”的图像框架(我说的对吗?)。我很确定 man.php 文件有问题,可能在 echo $row['image'] 中。 I am not sure how to go about making it right.我不知道如何使它正确。 Any help with this would be great.对此的任何帮助都会很棒。

If you want to retrieve the image which is stored as BLOB type in phpmyadmin you have to echo it as follows.如果要检索在 phpmyadmin 中存储为 BLOB 类型的图像,则必须按如下方式回显它。

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

Example:例子:

To Retrieve the BLOB image from the DB you have to do like this.要从数据库中检索 BLOB 图像,您必须这样做。

<?php
$db = mysqli_connect("localhost","root","","dbname"); //keep your db name
$query = "SELECT * FROM image WHERE id = $id";
$sth = $db->query($query);
$fetch=$sth->fetch_assoc();
echo '<img src="data:image/jpeg;base64,'.base64_encode( $fetch['image'] ).'"/>';
?>

For Inserting the image you need to follow the procedure like this So that if you encode it as base 64 you can retrieve the image perfectly without any error.对于插入图像,您需要遵循这样的过程,以便如果将其编码为 base 64,则可以完美地检索图像而不会出现任何错误。

<?php
$conn = mysqli_connect("localhost","root","","DbName"); //keep your db name
$single_image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//U have to keep your DB table column name for insertion. I keep image type Blob.
$query = "INSERT INTO image (image) VALUES('".$single_image."')";  
$SQL = mysqli_query($conn, $query);
?>

The function mysqli_close should be called after the image data is echoed.回显图像数据后应调用函数mysqli_close This is because it destroys the result sets.这是因为它破坏了结果集。

Also please fix the SQL Injection vulnerability:另外请修复 SQL 注入漏洞:

$imgId = (int)$_GET['id'];

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

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