Store and retrieve image from database using PHP and MySQL

  •  
  •  
  •  
  •  
  •  
  •  

Upload and store an image into the database and later retrieve that image from the database is very easy and simple. But before store into the database table, the image should be encoded using base64_encode() function. So, in this tutorial, I will show you how to store and retrieve image from database using PHP and MySQL. Also, you can learn from this tutorial about how to use base64_encode() to encode an image before upload to the database table.

You can test the live demo example on store and retrieve image from database using PHP and MySQL as well as can download the full source code from the download link.

Store and retrieve image from database using PHP and MySQL

 

 

Upload Image To The Server (index.php)

<form action="" method="post" id="form" enctype="multipart/form-data">
     Upload image : 
     <input type="file" name="uploadFile" value="" />
     <input type="submit" name="submitBtn" value="Upload" />
</form>

The above HTML code simply allows users to browse and choose an image from the local disk and upload it to the server.

Store Image Into The Database (index.php)

if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn'])) {
    if(isset($_FILES['uploadFile']['name']) && !empty($_FILES['uploadFile']['name'])) {
        //Allowed file type
        $allowed_extensions = array("jpg","jpeg","png","gif");
    
        //File extension
        $ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
    
        //Check extension
        if(in_array($ext, $allowed_extensions)) {
           //Convert image to base64
           $encoded_image = base64_encode(file_get_contents($_FILES['uploadFile']['tmp_name']));
           $encoded_image = 'data:image/' . $ext . ';base64,' . $encoded_image;
           $query = "insert into `images` set `encoded_image` = '".$encoded_image."'";
           mysqli_query($con, $query);
           echo "File name : " . $_FILES['uploadFile']['name'];
           echo "<br>";
           if(mysqli_affected_rows($con) > 0) {
              echo "Status : Uploaded";
              $last_insert_id = mysqli_insert_id($con); 
           } else {
              echo "Status : Failed to upload!";
           }
       } else {
           echo "File not allowed";
       }
  }
}

Example Explained

Apart from uploading, converting image into base4_encode and saving into database we also performing server side validation of the image.

$allowed_extensions = array(“jpg”,”jpeg”,”png”,”gif”) – Allowed image type that are to be uploaded.

$ext = strtolower(pathinfo($_FILES[‘uploadFile’][‘name’], PATHINFO_EXTENSION))  – Rteurns extension of the image in lowercase letter.

in_array($ext, $allowed_extensions) – It returns true if any match found otherwise returns false.

$encoded_image = base64_encode(file_get_contents($_FILES[‘uploadFile’][‘tmp_name’])) – Convert the image into base64 encoding format.

$encoded_image = ‘data:image/’ . $ext . ‘;base64,’ . $encoded_image – Prepend the data:image/jpg;base64 before the base64 encoded string. It is not necesary to do that here. You can also prepend the above string before the base64 encoded string in the src attribute of the <img /> tag.

$last_insert_id = mysqli_insert_id($con)  – It returns the id of the last inserted row from the database table.

Retrieve Image From The Database (index.php)

<?php
if($last_insert_id) {
  $query = "select `encoded_image` from `images` where `id`= ". $last_insert_id;
  $result = mysqli_query($con, $query);
  if(mysqli_num_rows($result) == 1) {
    $row = mysqli_fetch_object($result);
    echo "<br><br>";
    echo '<img src="'.$row->encoded_image.'" width="250">';
  }
}
?>

The above PHP code retrieves the record from the database table based on the id of the last inserted row. If anything returned then display the image on the web page.

Complete Source Code – Store and retrieve image from database using PHP and MySQL

Download the full source code from the below download link. Also, you can test and enjoy the live demo example on Store and retrieve image from database using PHP and MySQL. Please like and share the tutorial with others.

About Mitrajit

5 comments on “Store and retrieve image from database using PHP and MySQL

  1. Hello how can we create the database for this one.What are the fields to be included in the imges table

  2. Hello how can we create the database for this one.What are the fields to be included in the imges table.

Leave a Reply

Your email address will not be published. Required fields are marked *

Prove you are a human *