简体   繁体   中英

retrieve image from database using mysqli php 7

I am trying to retrieve a png image file from the database

Here is the call from within the <img> tag inside body:

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

Here's the man.php file:

<?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']. 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.

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.

<?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.

<?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. This is because it destroys the result sets.

Also please fix the SQL Injection vulnerability:

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

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