In previous tutorial I have posted an article about how to upload a file in PHP. In this article I am going to discuss about how to upload multiple image with few lines of code in php using jquery. In jQuery we are adding a script for dynamic select option of multiple images. It is similar code of file uploading with some modification in PHP code and adding a multiple attribute to to file input in html for selection of multiple file. Let us see the tutorial how to upload multiple images in PHP.
Also read:
Ajax image upload with jQuery and PHP
HTML
<h1 style="margin-top:0px;margin-left:150px;">How to upload multiple image dynamically Using Jquery</h1> <form method="POST" enctype="multipart/form-data"> <div id="container"> <div> <input type="file" name="image[]" multiple="" > <span id="add" class="badge">Add more</span><br> </div> </div> <input type="submit" name="upload" value="upload" class="btn btn-primary"> </form> </div>
Script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript">// <![CDATA[ $(document).ready(function(){ $('#add').on('click', function(){ var newfield = ' <div><input type="file" name="image[]" multiple=""><span class="remove badge">Remove</span></div> ' ; $('#container').append(newfield); }); $(document).on('click','.remove' , function(){ $(this).parent('div').remove(); }); }); </script>
DB
<?php mysql_connect("localhost","root",""); mysql_select_db("test"); ?>
PHP
<?php include('db.php') if(isset($_POST['upload'])) { foreach($_FILES['image']['name'] as $key=>$tmp_name) { $filename=$_FILES['image']['name'][$key]; $filetemp=$_FILES['image']['tmp_name'][$key]; if(move_uploaded_file($filetemp,"image/".$filename)){ { $sql=mysql_query("INSERT INTO `image`(`name`,`path`) VALUES('".$filename."','image/$filename')"); } } } if($sql){ echo '<div class="success">'; echo "uploaded succesfully"; echo '</div>'; } } ?>
CSS
#container{margin-left:450px;margin-top:50px;} span{ margin-left:250px; margin-top:-20px; } input[type="submit"] { margin-left: 451px; margin-top: 10px; } .success { margin-left: 451px; margin-top: 16px; }