PHP Ajax Upload Multiple Image with Preview Example

Upload multiple image with preview using jquery ajax + PHP + MySQL. in this tutorial, i am going to show you how to upload multiple image without refresh whole web page in PHP + MySQL + ajax with preview.

In this tutorial, i will use jQuery and ajax for display multiple images preview before upload to database and PHP project directory.

Upload Multiple Images using Ajax in PHP + MySQL with Preview

Follow the below given steps to upload multiple image using jQuery ajax in PHP + MySQL with preview:

  • Step 1 – Start Apache Web Server
  • Step 2 – Create PHP Project
  • Step 3 – Create Table and Database Connection File
  • Step 4 – Create Multiple Image Upload Html Form
    • Create Multiple Image Upload Form
    • Implement Ajax Code to Send Images into Server
  • Step 5 – Store Multiple Image into Database
  • Step 6 – Test This PHP App

Step 1 – Start Apache Web Server

Now, you need to start your apache web server. And as well as start Apache and mysql web server. You can see in the image below how to start apache and mysql server:

start xampp apache mysql server
start xampp apache mysql server

Step 2 – Create PHP Project

In step 2, navigate to your xampp/htdocs/ directory. And inside xampp/htdocs/ directory, create one folder. And you can name this folder anything.

Here, I will “demo” the name of this folder. Then open this folder in any text editor (i will use sublime text editor).

Step 3 – Create Table and Database Connection File

In step 3,, you need to create database and table. So run the following sql query to create database and table:

CREATE DATABASE my_db;


CREATE TABLE `images` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`file` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;

Then create a php file that named db.php. Which is used to connect phpmyadmin mysql database to project folder(demo).

So, now create db.php file and add the below given code into your file:

<?php

    $hName='localhost'; // host name

    $uName='root';   // database user name

    $password='';   // database password

    $dbName = "my_db"; // database name

    $conn = mysqli_connect($hName,$uName,$password,"$dbName");

      if(!$conn){
          die('Could not Connect MySql Server:' .mysql_error());
      }
?>

Step 4 – Create Multiple Image Upload Html Form

In step 4, create a php file that named index.php. Which is used to display multiple image preview before upload and store image file into MySQL database in PHP, So add the following code into it:

Create Multiple Image Upload Form

Create multiple Image upload form and add into index.php file; as shown below:

<html lang="en">
<head>
<title>How to upload and display multiple images in php + ajax - Laratutorials.com</title>

<!-- Bootstrap Css -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

</head>
<body>
<style type="text/css">
#preview img{
   margin: 5px;
}
</style>
<form method='post' action='' enctype="multipart/form-data">
   <input type="file" id='files' name="files[]" multiple><br>
   <input type="button" id="submit" value='Upload'>
</form>

<!-- Preview -->
<div id='preview'></div>
</body>
<script>
$(document).ready(function(){

$('#submit').click(function(){

   var form_data = new FormData();

   // Read selected files
   var totalfiles = document.getElementById('files').files.length;
   for (var index = 0; index < totalfiles; index++) {
      form_data.append("files[]", document.getElementById('files').files[index]);
 $('#preview').append("<img src='"+URL.createObjectURL(event.target.files[i])+"'>");
   }

   // AJAX request
   $.ajax({
     url: 'ajaxUpload.php', 
     type: 'post',
     data: form_data,
     dataType: 'json',
     contentType: false,
     processData: false,
     success: function (response) {
        alert("Uploaded SuccessFully");
        console.log(response);

     }
   });

});

});
</script>
</html>

Implement Ajax Code to Send Images into Server

Implement jQuery ajax code for send file to server, so add into index.php file; as shown below:

<script>
$(document).ready(function(){

$('#submit').click(function(){

   var form_data = new FormData();

   // Read selected files
   var totalfiles = document.getElementById('files').files.length;
   for (var index = 0; index < totalfiles; index++) {
      form_data.append("files[]", document.getElementById('files').files[index]);
 $('#preview').append("<img src='"+URL.createObjectURL(event.target.files[i])+"'>");
   }

   // AJAX request
   $.ajax({
     url: 'ajaxUpload.php', 
     type: 'post',
     data: form_data,
     dataType: 'json',
     contentType: false,
     processData: false,
     success: function (response) {
        alert("Uploaded SuccessFully");
        console.log(response);

     }
   });

});

});
</script>

Step 5 – Store Multiple Images into DB

In step 5, create one file that named ajaxUpload.php file. This php file code will insert/store multiple image file data into mysql database and directory.

Note that, If the Multiple image file upload is successfully inserted / stored into database, it will display success message. Otherwise if there is any error, it will display error message.

So, add the below code into your insert.php file:

<?php
require_once "db.php";

// Count total files
$countfiles = count($_FILES['files']['name']);

// Upload directory
$upload_location = "uploads/";

// To store uploaded files path
$files_arr = array();

// Loop all files
for($index = 0;$index < $countfiles;$index++){

   // File name
   $filename = $_FILES['files']['name'][$index];

   // Get extension
   $ext = pathinfo($filename, PATHINFO_EXTENSION);

   // Valid image extension
   $valid_ext = array("png","jpeg","jpg");

   // Check extension
   if(in_array($ext, $valid_ext)){

     // File path
     $path = $upload_location.$filename;

     // Upload file
     if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
        $files_arr[] = $path;

        mysqli_query($conn,"INSERT INTO images (file)
		VALUES ('".$path."')");
     }
   }

}

echo json_encode($files_arr);
die;

Step 6 – TestThis PHP App

Finally, you need to open your browser and type http://localhost/demo/ this run project on local machine.

Conclusion

To multiple image upload with preview using jquery ajax + PHP + MySQL. in this tutorial,you have learned how to upload multiple image without refresh whole web page in PHP + MySQL with ajax

Recommended PHP Tutorials

Leave a Comment