How to upload Multiple image in PHP MySQL Using Ajax

1 9,952

Hi Friend in this article we are Teach you how to upload multiple image in PHP MySQL using Ajax. We will simplify the upload multiple images without refreshing the page. using this script you can upload multiple images at once without page refresh using Ajax and PHP. We will show you two ways to display images after upload . Once the images are uploaded to the Server Ajax. and Second one is you can Display images stored in a Folder. This Script is easy and usefull which you can implemented in your web pages easily.

How to upload Multiple image in PHP MySQL Using Ajax

1-Creating Database

  • Open Phpmyadmin in your Browser
  • Click on Database Tab Display on Top side
  • Give the Database name “image_upload”.
  • After Creating Database Open it.
  • Click on SQL Tab on Top area
  • Copy the Below Source Code and paste it.
  • Then Click on Go.
-- phpMyAdmin SQL Dump
-- version 4.2.7.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Jun 29, 2016 at 02:48 PM
-- Server version: 5.6.20
-- PHP Version: 5.5.15

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `image_upload`
--

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

--
-- Table structure for table `user_uploads`
--

CREATE TABLE IF NOT EXISTS `user_uploads` (
`id` int(20) NOT NULL,
  `image_name` varchar(500) NOT NULL,
  `user_id_fk` varchar(500) NOT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user_uploads`
--
ALTER TABLE `user_uploads`
 ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user_uploads`
--
ALTER TABLE `user_uploads`
MODIFY `id` int(20) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=26;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

OR Import DB File

After Downloading the source code extract it in your root folder.

  • Open Phpmyadmin in your Browser
  • Click on Database Tab Display on Top side
  • Give the Database name “image_upload”.
  • After Creating Database Open it.
  • Click on Import Tab on Top area
  • You can Find Db file in  Downloaded source code Select it.
  • Then Click on Go.

2- Creating Database Connection

After import Database File then next step is creating database connection using php copy the below code and save it is as “db.php”.

<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "image_upload";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>

3- Create Form For upload Image

Next step is creating HTML Simple Form for upload images. input field name is defined as an array for accept multiple image name and also used multiple attributes for multiple upload.

<form id="form_Images" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
<h1>Upload Multiple images</h1> 
<div id='status_image_Loading' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='button_Image_loading'>
<input type="file" name="photos[]" class="file_image" id="image_Photo" multiple="true" />
</div>
</form>

4- Make Attractive using CSS

in this step give some style to form using css and make more attractive. follow these step given below.

<style>

body
{
font-family:lobaster;
}

#preview_Upload_images
{
color:#cc0000;
font-size:12px
}
.imgList 
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px;	
float:left;	
}
h1 {
	font-family:lobaster;
}
.file_image {
	border:2px solid red;
	font-size:18px;
	font-family:lobaster;
	padding:8px;
}
</style>

5 – Validating The Form Using PHP

in this step contain PHP Script for validating the form serverside.

 <?php
error_reporting(0);
session_start();
include('db.php');

$session_id='1'; //$session id
define ("MAX_SIZE","9000"); 
function getExtension($str)
{
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}


$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") 
{
	
    $uploaddir = "uploads/"; //a directory inside
    foreach ($_FILES['photos']['name'] as $name => $value)
    {
	
        $filename = stripslashes($_FILES['photos']['name'][$name]);
        $size=filesize($_FILES['photos']['tmp_name'][$name]);
        //get the extension of the file in a lower case format
          $ext = getExtension($filename);
          $ext = strtolower($ext);
     	
         if(in_array($ext,$valid_formats))
         {
	       if ($size < (MAX_SIZE*1024))
	       {
		   $image_name=time().$filename;
		   echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
		   $newname=$uploaddir.$image_name;
           
           if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) 
           {
	       $time=time();
	       mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
	       }
	       else
	       {
	        echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>';
            }

	       }
		   else
		   {
			echo '<span class="imgList">You have exceeded the size limit!</span>';
          
	       }
       
          }
          else
         { 
	     	echo '<span class="imgList">Unknown extension!</span>';
           
	     }
           
     }
}

?>

6- Form Submission Without Page Refresh using Ajax

at first include the two external Jquery library files , “jquery.min.js” and “jquery.wallform.js”. First Library file is the main Jquery library and another file is used to submit the form with files for uploading using JQuery Ajax. You can download JQuery Library File online.

<script src="js/jquery.min.js"></script>
<script src="js/jquery.wallform.js"></script>

Write Ajax Code for Form Submission and Displaying the uploaded images.

<script>
 $(document).ready(function() { 
		
            $('#image_Photo').die('click').live('change', function()			{ 
			           //$("#preview_Upload_images").html('');
			    
				$("#form_Images").ajaxForm({target: '#preview_Upload_images', 
				     beforeSubmit:function(){ 
					
					console.log('ttest');
					$("#status_image_Loading").show();
					 $("#button_Image_loading").hide();
					 }, 
					success:function(){ 
				    console.log('test');
					 $("#status_image_Loading").hide();
					 $("#button_Image_loading").show();
					}, 
					error:function(){ 
					console.log('xtest');
					 $("#status_image_Loading").hide();
					$("#button_Image_loading").show();
					} }).submit();
			});
        }); 
</script>

If you facing any type of problem with this source code then you can Download the Complete source code in zip Formate by clicking the below button Download Now otherwise you can send Comment.

Download Source Code

1 Comment
  1. Deborah Edwards says

    You got a very wonderful website, Glad I discovered it through yahoo.

Leave A Reply

Your email address will not be published.