Save Image Directly Into MySQL Database Without Local Storage

In this article, We are going to see how to save images directly into the database without local storage.

If we do have not space in local storage so we can also upload and save images in a directory of the server.

we can retrieve an image from the database and display it on the webpage.

Insert Image in MySQL

What is BLOB?

MySQL has a BLOB (binary large object) data type that can hold a large amount of binary data. A BLOB is a binary large object that can hold a variable amount of data.

The actual BLOB column type is of four types-TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB.

Create Table into Database:

In Which, we use a LONGBLOB data type field to save an image in the database.

CREATE TABLE `save_images` (
  `image` longblob NOT NULL,
  `uploaded` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Create Database Configuration File:

The config.php file is used to connect with the database.

// Database configuration  
$server     = "localhost";
$username   = "root";
$password   = "";
$database   = "codehubs";

// Create database connection  
$conn = mysqli_connect($server, $username, $password, $database);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());

Create HTML Form File:

The index.php file is used to create HTML Form.

<!DOCTYPE html>
<html lang="en">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Blog Form</title>
  <link href="" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">		
  <script src=""></script>
  <div class="container">
    <div class="card mt-5">
      <div class="card-header">Image Form</div>
      <div class="card-body">
      <form id="form" action="uploadimage.php" method="post" role="form" enctype="multipart/form-data">			
        <div class="row">
          <div class="col-md-6 mb-3"> 
            <label class="pb-2">Select Image</label></br> 
            <input class="file" type="file" name="image" onchange="readURL(this);">	
          <div class="col-md-6 mb-3">
            <img id="blah" src="#" alt="wallpaper" style="visibility: hidden;" />
        <input class="btn btn-primary" type="submit" name="submit" value="Upload Image">
        <a href="viewimage.php" class="btn btn-primary" >View Images</a>
    function readURL(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {

Create upload image File:

The uploadimage.php file is used to upload images in the database.

// Include the database configuration file  
// If file upload image is submitted 
$error = '';
$msg = ''; 
$status = ''; 
    $error = 'error'; 
    if(!empty($_FILES["image"]["name"])) { 
        // Get file information 
        $fileName = basename($_FILES["image"]["name"]); 
        $fileType = pathinfo($fileName, PATHINFO_EXTENSION); 
        // Allow below file formats 
        $allowTypes = array('jpg','png','jpeg','gif'); 
        if(in_array($fileType, $allowTypes)){ 
            $image = $_FILES['image']['tmp_name']; 
            $imgfile = addslashes(file_get_contents($image)); 
      $uploadedtime = date("Y-m-d H:i:s");
            // Insert image into database 
            $insert = $conn->query("INSERT into save_images (image, uploaded) VALUES ('$imgfile', '$uploadedtime')"); 
                $status = 'success'; 
                $msg = "File uploaded successfully."; 
                $msg = "File upload failed, please try again."; 
            $msg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        $msg = 'Please select an image to upload.'; 

// Display All message 
echo $msg; 

//If file uploaded successfully
if( !empty($status) ) {
  header( 'Location: viewimage.php' );

Create view image File:

The viewimage.php file is used to retrieve images from the database and display them on the front page.

In which, The data, charset, and base64_encode parameters in the src attribute are used to display image BLOB from the MySQL database. The image file converts the base64_encode.

what is base64_encode?

base64_encode — Encodes data with MIME base64.

// Include the database configuration file  
// Display image from database 
$result = $conn->query("SELECT image FROM save_images"); 

<?php if($result->num_rows > 0){ ?> 
    <div class="portfolio"> 
        <?php while($row = $result->fetch_assoc()){ ?> 
            <img src="data:image/jpg;charset=utf8;base64,<?php echo base64_encode($row['image']); ?>" /> 
        <?php } ?> 
<?php }else{ ?> 
    <p class="msg">Images not found....</p> 
<?php } ?>


Thank You, hope you guys found something useful.

Submit a Comment

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


Select Categories