Multiple image upload concept using php & mysql - Mostlikers

04 March, 2014

Multiple image upload concept using php & mysql

In this tutorial, We are going to see How to upload multiple images using PHP and MySQL. Sometimes we need to allow user upload multiple images in the database. Once the user has uploaded multiple images we must need to provide image edit, delete option. Previously  I have used to stored all the images name in single table column for using implode() and explode() function. Later I'm facing issues on to delete or modified particular uploaded images.  

multiple image upload using php and mysql


Live Demo          Download

So, Later I have modified this PHP script on a single table. It's an easy way to add a new image, Edit, Delete based on users id. Here I have shared only to how to add multiple images in a single table. Soon I will update multiple images add with edit and delete using ajax.


Database

Create a new table name as  'gallery' with below column structure. 
CREATE TABLE IF NOT EXISTS `gallery` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(250) NOT NULL,
  PRIMARY KEY (`id`)
)

Database Connection

creates a new file as config.php then paste the copied below code inside the file. Make sure check the connection query was execute or not.
<?php
$db_username    = 'root';
$db_password    = '';
$db_name        = 'db_name';
$db_host        = 'localhost';
$db = new mysqli($db_host, $db_username, $db_password,$db_name);
if(!$db) {
echo 'connection failed'; exit;
}
?>


Create new upload Directory

Create new folder directory in your project path. make the folder name as uploads. This folder we are storing all users uploaded images.  
Folder path : htdocs/Project folder/uploads


Load Html Code to the index Page

Create a new file (index.php). then paste the copied below code inside the file. Don't forget to add form encrypt code.
  • images[] - Name of the attribute, [] array of the input field.
  • accept="image/*" - This code only accept the images format.
<html>
<body>
  <form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file"  name="images[]"  multiple="multiple" accept="image/*" />
  <input type="submit" name="sub" value="Upload!" />
  </form>
</body>
</html>

Upload.php

The upload.php file contains some PHP codes for the process the uploading images. After images upload to the database page will be redirected to the index.php 

  • $path ='uploads/' - files will move on uploads folder.
  • filesize - get uploaded image specify size.     
<?php
include('config.php');
error_reporting(0);     
if(isset($_FILES['images']['name'])):
  define ("MAX_SIZE","2000");
  for($i=0; $i<count($_FILES['images']['name']); $i++)  {
  $size=filesize($_FILES['images']['tmp_name'][$i]);    
  if($size < (MAX_SIZE*1024)):    
   $path = "uploads/";
   $name = $_FILES['images']['name'][$i];
   $size = $_FILES['images']['size'][$i];
   list($txt, $ext) = explode(".", $name);
   date_default_timezone_set ("Asia/Calcutta"); 
   $currentdate=date("d M Y");  
   $file= time().substr(str_replace(" ", "_", $txt), 0);
   $info = pathinfo($file);
   $filename = $file.".".$ext;
    if(move_uploaded_file($_FILES['images']['tmp_name'][$i], $path.$filename)) :
       $fetch=$db->query("INSERT INTO gallery(image) VALUES('$filename')");
       if($fetch):
         header('Location:index.php');
       else :
         $error ='Data not inserting';
       endif;
    else :
        $error = 'File moving unsuccessful';
    endif;
  else:
     $error = 'You have exceeded the size limit!';
  endif;      
  }
else:
  $error = 'File not found!';
endif;          
?>
<h2><?php echo @$error ?></h2> <a href="index.php">Try Again</a>

Display uploaded images in PHP

For load, all the inserted images use below code. It will display all the uploaded images.

<html>
<body>
<?php include('config.php');    
  $sql = $db->query("SELECT * FROM gallery");
    if(isset($sql) && count($sql)) :  
      foreach ($sql as $key => $row) : ?>    
       <img src="uploads/<?php echo $row['image']; ?>" /> 
<?php endforeach;   endif; ?>
</body>
</html>






Have a Question? Share your feedback below.

"Excellence is a continuous process and not an accident. "
                                             
                                         - A. P. J. Abdul Kalam



20 comments:

  1. But why is the database still empty? though its working

    ReplyDelete
  2. thanks for for the code but when it did not store the all image path. it only store the last image name not path.

    ReplyDelete
    Replies
    1. check your file type name array format image[]

      $image_path=$filename.$path;
      $fetch=$db->query("INSERT INTO gallery(image) VALUES('$image_path')");

      Delete
  3. I also want to insert path in database

    ReplyDelete
  4. But the form is allowing to upload one image at a time and overwrites the previous if loaded multiple images

    ReplyDelete
    Replies
    1. faced the same situation and no data is inserted in the database even though the connection works

      Delete
  5. hey bro its only store 1 images in database.....how we can store multiple images guide us.

    ReplyDelete
    Replies
    1. The above code will work multiple image.

      Delete
  6. bro how about edit them? guide me please
    thanks in advance

    ReplyDelete
  7. POST Content-Length of 11760096 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

    ReplyDelete
    Replies
    1. 8388608 bytes is 8M, the default limit in PHP. Update your post_max_size in php.ini to a larger value.
      upload_max_filesize sets the max file size that a user can upload while post_max_size sets the maximum amount of data that can be sent via a POST in a form.

      Delete
  8. i'm a beginner in php this is my upload edit and delet image coad.............but something is wrong bez my output did not show product_picture other only product_picture1 was show in this output page....and also edit buton dose not working...but image insert in database proper ...... i don't know where is my mistake plz help me





    ReplyDelete
    Replies
    1. $path = "uploads/"; Have you create uploads folder with 777 permission

      Delete