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` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `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.

<?php  
// 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">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Blog Form</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">		
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>
<body>
  <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>
          <div class="col-md-6 mb-3">
            <img id="blah" src="#" alt="wallpaper" style="visibility: hidden;" />
          </div>
        </div>
        <input class="btn btn-primary" type="submit" name="submit" value="Upload Image">
        <a href="viewimage.php" class="btn btn-primary" >View Images</a>
      </form>
      </div>
    </div>
  </div>
  <script>
    function readURL(input) {
      if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
          $('#blah').css("visibility","visible");
          $('#blah')
            .attr('src', e.target.result)
            .width(100)
            .height(100);
        };
        reader.readAsDataURL(input.files[0]);
      }
    }
  </script>
</body>
</html>

Create upload image File:

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

<?php 
// Include the database configuration file  
include("Config.php");
 
// If file upload image is submitted 
$error = '';
$msg = ''; 
$status = ''; 
if(isset($_POST["submit"])){ 
    $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')"); 
             
            if($insert){ 
                $status = 'success'; 
                $msg = "File uploaded successfully."; 
            }else{ 
                $msg = "File upload failed, please try again."; 
            }  
        }else{ 
            $msg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        } 
    }else{ 
        $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.

<?php 
// Include the database configuration file  
include("Config.php");
 
// 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 } ?> 
    </div> 
<?php }else{ ?> 
    <p class="msg">Images not found....</p> 
<?php } ?>

Output:


Thank You, hope you guys found something useful.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories