Wednesday, 14 November 2018

How to Store Multiple Images in Database using PHP Ajax



In Web development file or image upload is a very required feature. There are many ways we can store images. One we can upload image on server and store image name in Mysql database using PHP. In another way we can directly store images in Mysql database table using PHP also. There are many post we have publish on upload single image or multiple images on server and store image details in database using PHP. But in this post we have convered one advance topic like how to insert multiple image in mysql database using PHP with Ajax.

In one of our previous post we have step by step describe how to insert and fetch images from Mysql database using PHP. But in that post we have use only PHP script for insert image into mysql database and then after fetch images from Mysql database and display on web page using PHP. But here we have make one form with option like select multiple images at the same time and by using jQuery Ajax send that images data to PHP. In PHP script it will convert image into binary string format and insert into Mysql database one by one. After inserting multiple images into Mysql database, now we want to retrieve images from mysql database and display on web page. For this also we have use jQuery and Ajax function which send request to PHP, at PHP script that fetch data from mysql table and convert that data into html format and send back to ajax request. Now we have discuss source of How to Upload Multiple Images in Database using PHP Ajax.








Mysql Database


Run following SQL script into your phpMyadmin, this script will make tbl_images table into your database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_images`
--

CREATE TABLE `tbl_images` (
  `image_id` int(11) NOT NULL,
  `images` longblob NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_images`
--
ALTER TABLE `tbl_images`
  ADD PRIMARY KEY (`image_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_images`
--
ALTER TABLE `tbl_images`
  MODIFY `image_id` int(11) NOT NULL AUTO_INCREMENT;


database_connection.php


This PHP script will make Mysql database connection.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

?>


index.php


This index file of this source code in this file you can find following things.

  • HTML form for select multiple images from local computer space with image selection validation.
  • jQuery script for submit form data to PHP script using Ajax.
  • Selected image has been send to PHP script using new FormData() object.
  • Ajax script send request for images and display on web page.



<!DOCTYPE html>  
<html>  
    <head>  
        <title>Webslesson Tutorial | Insert Multiple Images into Mysql Database using PHP</title>  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
    </head>  
    <body>  
        <br /><br />  
        <div class="container">  
   <h3 align="center">Insert Multiple Images into Mysql Database using PHP</h3>  
            <br />  
            <form method="post" id="upload_multiple_images" enctype="multipart/form-data">
                <input type="file" name="image[]" id="image" multiple accept=".jpg, .png, .gif" />
                <br />
                <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
            </form>
            <br />  
            <br />
   
            <div id="images_list"></div>
            
        </div>  
    </body>  
</html>  
<script>  
$(document).ready(function(){

    load_images();

    function load_images()
    {
        $.ajax({
            url:"fetch_images.php",
            success:function(data)
            {
                $('#images_list').html(data);
            }
        });
    }
 
    $('#upload_multiple_images').on('submit', function(event){
        event.preventDefault();
        var image_name = $('#image').val();
        if(image_name == '')
        {
            alert("Please Select Image");
            return false;
        }
        else
        {
            $.ajax({
                url:"insert.php",
                method:"POST",
                data: new FormData(this),
                contentType:false,
                cache:false,
                processData:false,
                success:function(data)
                {
                    $('#image').val('');
                    load_images();
                }
            });
        }
    });
 
});  
</script>





insert.php


This insert.php file, in this file you can find PHP script for Insert Multiple images into Mysql database. This file has received ajax request for insert multiple file into Mysql database. First, this script check there is any image file has been received or not, if received then it will check how many image insert has been received. After this this PHP script insert images into Mysql database. Before insert imag into mysql database, first it has convert into binary string format using file_get_contents() function and then at it has make insert query and run insert query and store multiple images into mysql database.


<?php

//insert.php

include('database_connection.php');

if(count($_FILES["image"]["tmp_name"]) > 0)
{
 for($count = 0; $count < count($_FILES["image"]["tmp_name"]); $count++)
 {
  $image_file = addslashes(file_get_contents($_FILES["image"]["tmp_name"][$count]));
  $query = "INSERT INTO tbl_images(images) VALUES ('$image_file')";
  $statement = $connect->prepare($query);
  $statement->execute();
 }
}


?>


fetch_images.php


This PHP script received Ajax request for retrieve images from Mysql database. This PHP script retrieve images from Mysql database and after this convert into HTML format and send to Ajax request. For convert binary string to images, here we have use base64_encode() function.


<?php

//fetch_images.php

include('database_connection.php');

$query = "SELECT * FROM tbl_images ORDER BY image_id DESC";

$statement = $connect->prepare($query);

$output = '<div class="row">';

if($statement->execute())
{
 $result = $statement->fetchAll();

 foreach($result as $row)
 {
  $output .= '
  <div class="col-md-2" style="margin-bottom:16px;">
   <img src="data:image/jpeg;base64,'.base64_encode($row['images'] ).'" class="img-thumbnail" />
  </div>
  ';
 }
}

$output .= '</div>';

echo $output;

?>

4 comments: