How to upload multiple images with preview using Ajax in PHP and MySQL

Using Ajax with PHP and MySQL we can upload multiple images, preview them before upload and also we can delete any uploaded image without a page refresh. In this topic, we will develop this application to select multiple images and upload them using Ajax.

For single image upload using Ajax, you can read the topic How to preview and upload a photo without page refresh using Ajax in PHP.

Purpose of this topic is to show how you can write PHP code to upload one or more photos and view them instantly using PHP, Ajax and MySQL.

Upload Multiple Image with Preview in PHP Using jQueryAssumption

  1. You must have basic knowledge in PHP with HTML, CSS, JavaScript and jQuery.
  2. You must have basic understanding of Ajax. You can read below topics for more details:
    1. How to install xampp for Windows with setup for PHP development
    2. How to write PHP code with examples for beginners
    3. How to build a simple CRUD application in PHP and MySQL

Upload multiple images using jquery, PHP and AjaxFolders and Files

Below is a screenshot of the folder structure and files I am using:

Multiple image upload with preview

I have created a folder named 'images' under 'xampp/htdocs' as I am using XAMPP. If you are using WAMP, create 'images' folder under 'www'.

  1. Folder 'cfg' - In this folder I have kept dbconnect.php which is used to connect to the MySQL database.
  2. Folder 'css' - My custom stylesheet is in this folder
  3. Folder 'js' - In this folder I have my custom JavaScripts file
  4. Folder 'uploads' - All uploaded photos will be stored in this folder
  5. index.php is the screen where user can upload, view and delete photos.
  6. process_image.php is the PHP program called from Ajax. This PHP program is to upload, delete and display photos.

Below is the screenshot of the page:

multiple image upload with preview and delete javascript

Step 1 - Create a table in MySQL database to store image files

Let us create a table named 'images' in MySQL database. I have a database called 'demo'. So, this table will be created in demo database. If you have an existing database other than demo you can also use it. Just make sure same table does not exist already. Table structure and create table scripts are given below:

Table: images

This table stores images names of all uploaded images

Preview images before upload

Table has 3 columns.

  1. id - Unique id of each image, it is the primary key and auto incremented
  2. image_file - File name of uploaded image
  3. upload_dt - Date on which image was uploaded
Create table script for this table is given below, you can use this code to create the table. Also, if you download code (see in download section) you will get all the scripts.

images.sql

After you create the table, verify if structure is same as above.

Step 2 - Connect to MySQL database (dbconnect.php)

Use below script to connect to the database. Note that we have this database connection php program in 'cfg' folder. This is written once and used in every program where database connection is needed. This will be easy for maintenance and also will enable reusability of the code.

dbconnect.php

I am using mysqli_connect() function which needs 4 parameters.

  1. server - in our case it is localhost
  2. userid - we are using root user
  3. password - no password for user root
  4. database name - demo in our case.

If connection is successful then it will return true and false otherwise. We will include this dbconnect.php in other php programs so that we do not need to write it again in the program. For detail database connection understanding please read topic How to Connect to MySQL database in PHP using mysqli_connect.

Step 3 - Develop a screen to upload and view photos (index.php)

Our upload page will look like below. As soon as one or more photos are uploaded, these photos including previously uploaded photos will be displayed on the right side under view photos. User can select maximum 5 photos at a time to upload. System will give message if more than 5 photos are selected for upload. I have added this just to show that you can limit number of photos to upload at a time. You can change it to any value you want. User can also delete a photo from right side by clicking on 'x' button on top right corner of a photo. Also, user can click on a photo and view larger size of the photo in a modal.

how to upload and display multiple images in php

As soon as photos are selected, preview of the selected photos will be displayed just above "Upload Photo" button.

Let's see the code for left hand side of the screen to upload and preview photos.

Here, I will use a file input field to select multiple files. Then I will have a space for preview the photos and then an "Upload Photo" button.

A JavaScript function previewImage() is called on onChange event of this field. So, when a file is selected, this event will be triggered. Initially, upload button is disabled and when one or more files are selected, it will be enabled.

Now, let's see the code for the right side of the screen which is used to display all uploaded images with option to delete. Here, I am displaying uploaded images from the 'images' table.

In a loop, I am fetching all images and displaying them. See below code:

Image source is the image name from database and the path is the "uploads" folder. During upload, image name is stored in the database and the image file is uploaded in "uploads" folder. Also, see that image is given in a link to display it in a modal when it is clicked. On clicking on delete button, deleteImage() function is called to delete the image. A modal is defined as below in index.php.

Here is the complete code for index.php

index.php

Step 4 - Write JavaScript/jQuery to preview, upload and delete photos (image_scripts.js)

Preview Image - Function previewImage()

This function displays the preview of one or more images selected by the user. It checks number of files selected, I have given 5 as the maximum number of files one can select at a time. You can change to any reasonable value. Let's see the code for this function:

Upload button is defined in index.php with id as "btnUpload" and it is disabled initially. In a loop each image is taken from the array and file name is validated, if validation is passed, image is displayed. Image source is created as an URL using URL.createObjectURL() function.

Function to upload images

Now, let us see what happens when upload button is clicked by the user. Upload button is used to upload the photos in the server. We will write a function on onClick event of this button. This function executes an Ajax script to run a php program (process_image.php) with the input files as parameter to upload the photos. Let's see the Ajax code:

An instance of FormData() is created and adding the input image files in form_data. Then executing an Ajax script with the form_data as one of the parameters. Let's see all the parameters in Ajax call below:

  1. url: process_image.php - Call to php program which uploads the images.
  2. dataType: text - Response of Ajax call is text only
  3. cache: false - We do not want browser to cache
  4. contentType: false - Since we are sending form_data with image file as input, we must set contentType as false to use enctype = multipart/form-data
  5. processData: false - This is also for form data, we do not want jQuery to process data before sending it to the server.
  6. data: form_data - input data sent to the request
  7. type: post - Type must be post here for enctype = multipart/form-data
  8. success: When Ajax successfully gets response, I am writing response message about upload. I am writing these messages just below the upload button. Also, upload button is disabled and image previews are removed. Function reloadImages() refreshes the images displayed on the right side of the screen.
  9. error: In case of any error, we just need to print the error message.

I need to explain two things here, one - process_image.php, other JavaScript function reloadImages().

process_image.php uploads, deletes images and also displays images. Let us see upload section of process_image.php.

mysqli autocommit is set as false, because there will a database insert for each image as well as an upload of the image file to the server. Both these functions should complete successfully, if one fails we do not want other to complete. So, we can rollback if upload fails and commit if upload is a success.

If validations are successful, we insert the image file name with date in database table 'images'. If database insert is successful, I upload the file using move_uploaded_file() php function.

Hope you understood the upload image function using Ajax.

Function reloadImages()

This function is used to refresh image list displayed on the right side of the screen. Below is the screenshot of the images displayed after uploading. I have already explained in index.php about how these are displayed on the right side of the screen. Now let's see how the list is refreshed using Ajax.

PHP Ajax Multiple Image Upload with Preview Example

You can see this is also an Ajax call and calling the same php program process_image.php. See data parameter where I am sending reload as true.

Now let's look at the code in process_image.php, used in above Ajax call, that reloads the images.

Note that it is the same code written in index.php where images are displayed on the right side of the screen. A JavaScript function deleteImage() is called on onclick event of the delete button.

Function deleteImage()

This function is called when user clicks on delete (x -button) button from top right corner of an image. Function executes Ajax scripts to run process_image.php which deletes the image from database as well as removes the image file from the server folder ('uploads' in our case). Below is the code for this function.

After an image is deleted, reloadImages() function is called to refresh all images. Let's see the code for delete section of process_image.php.

To display image in modal when user clicks on the image, below script is written in image_scripts.js.

I have given complete code of image_script.js and process_image.php below. There is a download section later in this topic, if you download the zip file, you will get all the scripts for this topic.

image_script.js

process_image.php

Step 5 - Add CSS (style.css)

We need to add some styles. Very simple and basic styles are used here. You can always add better styles. I have already added style.css in index.php. See below:

style.css

PHP Ajax Multiple Image Upload with Preview ExampleTest the Application

Make sure in your XAMPP control panel, Apache and MySQL services are running. Open the browser and run localhost/images. You will see the home page as displayed below:

Upload multiple images in PHP and Ajax

Select few images (max 5, press Ctrl key to select multiple) and see if you are able to see the preview of the photos. Upload button should now be enabled. Click on it, photos will be uploaded and you should see them on the right side. Click on any photo, it should open in a modal. Also delete a photo and see the list is refreshed.

PHP Upload Multiple Files via AJAX using jQuery

Hope you could understand all the steps and you could test it successfully.

PHP Ajax Multiple Image UploadImportant Note

For uploading images, you must verify below parameters in php.ini file. Below are the values set for these parameters in my php.ini

download source code for uploading multiple images in PHP and AjaxDownload Source Code

I have put all codes in a zip file. You can download it by clicking on the Download button below. You do not need to register yourself to download it. You can directly use the code or you can modify them as per your requirements.

upload multiple images in PHP and Ajax and mysqlConclusion

In this example I have showed you how you can preview, upload and delete images using Ajax without submitting a form. If you find it useful, you can use it in your project or any other web application with similar requirement.