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;

?>

18 comments:

  1. when i upload image.....then it show no file chosen

    ReplyDelete
  2. can give me source code
    thank

    ReplyDelete
  3. thank you for sharing such a nice stuff

    ReplyDelete
  4. https://eduproblem.xyz/laravel-multiple-images-upload-laravel-image-upload/
    see this hope that solve your problem

    ReplyDelete
  5. image is not inserting....after submiting it shows choose file

    ReplyDelete
  6. How does one update or delete selected images

    ReplyDelete
  7. Hey friend
    Thanks lot for that great job
    ✌🏽

    ReplyDelete
  8. It says: Warning: count(): Parameter must be an array or an object that implements Countable. What to do?

    ReplyDelete
  9. Hi.. great tutorial but I am having a problem to execute move_uploaded_file() in insert.php. Can you tell me what the problem is?

    ReplyDelete
  10. Please you can upload again the demo? because are hacked by some idiot

    ReplyDelete
    Replies
    1. Thanks for show us this issue, we have fixed it and now you can check online demo, it is working now.

      Delete