Multiple images uploading option is very handy if you want to upload more than one image at a time. Because multiple images upload option save lots of time of the user.
In this tutorial I am going to show you how to upload multiple images in PHP and store in mysql. I am going to create dynamic input fields using jquery and save them in mysql table.
How Upload multiple Images in PHP works:
- First I will create a html form with one file input field.
- Second i will add jquery code to create dynamic file input fields.
- Third write PHP code for file type validation, image size restriction and move images to target folder.
- Four if image successfully transfer to target folder then i will save image name in the database.
Also read:
- jQuery Zoom Image on Hover
- How to display images from folder in PHP
- PHP Download, Crop and Save Image in a Folder from URL
- User Registration in PHP
Create Mysql Database:
1 2 3 4 |
Create database demo; Use demo; |
Create Mysql Table:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
CREATE TABLE `images` ( `id` int(11) NOT NULL, `image` varchar(255) NOT NULL, `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `images` ADD PRIMARY KEY (`id`); ALTER TABLE `images` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; |
Upload Form HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<div class="form-container"> <?php if(isset($successMsg) && !empty($successMsg)) { echo "<div class='success-msg'>"; foreach($successMsg as $sMsg) { echo $sMsg."<br>"; } echo "</div>"; } ?> <?php if(isset($errorMsg) && !empty($errorMsg)) { echo "<div class='error-msg'>"; foreach($errorMsg as $eMsg) { echo $eMsg."<br>"; } echo "</div>"; } ?> <div class="add-more-cont"><a id="moreImg"><img src="img/add_icon.jpg">Add Image</a></div> <form name="uploadFile" action="" method="post" enctype="multipart/form-data" id="upload-form"> <div class="input-files"> <input type="file" name="image_upload-1"> </div> <input type="submit" name="submit" value="submit"> </form> </div> |
File upload form must have enctype=”multipart/form-data” attritube.
jQuery Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ var id = 1; $("#moreImg").click(function(){ var showId = ++id; if(showId <=10) { $(".input-files").append('<input type="file" name="image_upload-'+showId+'">'); } }); }); </script> |
PHP Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
<?php $conn = mysqli_connect('localhost','root','root','demo'); if(!$conn) { die(mysqli_error()); } if(isset($_POST['submit'])) { $targetFolder = "uploads"; $errorMsg = array(); $successMsg = array(); foreach($_FILES as $file => $fileArray) { if(!empty($fileArray['name']) && $fileArray['error'] == 0) { $getFileExtension = pathinfo($fileArray['name'], PATHINFO_EXTENSION);; if(($getFileExtension =='jpg') || ($getFileExtension =='jpeg') || ($getFileExtension =='png') || ($getFileExtension =='gif')) { if ($fileArray["size"] <= 500000) { $breakImgName = explode(".",$fileArray['name']); $imageOldNameWithOutExt = $breakImgName[0]; $imageOldExt = $breakImgName[1]; $newFileName = strtotime("now")."-".str_replace(" ","-",strtolower($imageOldNameWithOutExt)).".".$imageOldExt; $targetPath = $targetFolder."/".$newFileName; if (move_uploaded_file($fileArray["tmp_name"], $targetPath)) { $qry ="insert into images (image) values ('".$newFileName."')"; $rs = mysqli_query($conn, $qry); if($rs) { $successMsg[$file] = "Image is uploaded successfully"; } else { $errorMsg[$file] = "Unable to save ".$file." file "; } } else { $errorMsg[$file] = "Unable to save ".$file." file "; } } else { $errorMsg[$file] = "Image size is too large in ".$file; } } else { $errorMsg[$file] = 'Only image file required in '.$file.' position'; } } } } ?> |
$targetFolder
holds the “Uploads” directory name. $errorMsg
and $successMsg
are arrays of error and success messages. Then I started loop on $_FILES
and checked $fileArray['name']
and $fileArray['error']
must not be empty and zero. $getFileExtension
holds the extension of images. If user upload any file other than image code will print an error. Then i checked size of image which should not more than 500kb. $breakImgName
is used to break the image name. $newFileName
is used to create new image name by using strotime
and str_replace
function. $targetPath
variable holds the new image path. move_uploaded_file
function is used to move image from temporary storage to the targeted path. If image moved properly then image name is saving to the images table.
All upload multiple images Code together
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
<?php $conn = mysqli_connect('localhost','root','root','demo'); if(!$conn) { die(mysqli_error()); } if(isset($_POST['submit'])) { $targetFolder = "uploads"; $errorMsg = array(); $successMsg = array(); foreach($_FILES as $file => $fileArray) { if(!empty($fileArray['name']) && $fileArray['error'] == 0) { $getFileExtension = pathinfo($fileArray['name'], PATHINFO_EXTENSION);; if(($getFileExtension =='jpg') || ($getFileExtension =='jpeg') || ($getFileExtension =='png') || ($getFileExtension =='gif')) { if ($fileArray["size"] <= 500000) { $breakImgName = explode(".",$fileArray['name']); $imageOldNameWithOutExt = $breakImgName[0]; $imageOldExt = $breakImgName[1]; $newFileName = strtotime("now")."-".str_replace(" ","-",strtolower($imageOldNameWithOutExt)).".".$imageOldExt; $targetPath = $targetFolder."/".$newFileName; if (move_uploaded_file($fileArray["tmp_name"], $targetPath)) { $qry ="insert into images (image) values ('".$newFileName."')"; $rs = mysqli_query($conn, $qry); if($rs) { $successMsg[$file] = "Image is uploaded successfully"; } else { $errorMsg[$file] = "Unable to save ".$file." file "; } } else { $errorMsg[$file] = "Unable to save ".$file." file "; } } else { $errorMsg[$file] = "Image size is too large in ".$file; } } else { $errorMsg[$file] = 'Only image file required in '.$file.' position'; } } } } ?> <!DOCTYPE html> <html> <head> <title>how to upload multiple images in php and store in mysql database</title> <link rel="stylesheet" href="style.css" type='text/css'> </head> <body> <div class="form-container"> <?php if(isset($successMsg) && !empty($successMsg)) { echo "<div class='success-msg'>"; foreach($successMsg as $sMsg) { echo $sMsg."<br>"; } echo "</div>"; } ?> <?php if(isset($errorMsg) && !empty($errorMsg)) { echo "<div class='error-msg'>"; foreach($errorMsg as $eMsg) { echo $eMsg."<br>"; } echo "</div>"; } ?> <div class="add-more-cont"><a id="moreImg"><img src="img/add_icon.jpg">Add Image</a></div> <form name="uploadFile" action="" method="post" enctype="multipart/form-data" id="upload-form"> <div class="input-files"> <input type="file" name="image_upload-1"> </div> <input type="submit" name="submit" value="submit"> </form> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ var id = 1; $("#moreImg").click(function(){ var showId = ++id; if(showId <=10) { $(".input-files").append('<input type="file" name="image_upload-'+showId+'">'); } }); }); </script> </body> </html> |
Also read: