Upload Multiple Files to Store in MySQL Database Using PHP

Are you want to learn How to upload multiple files and store them in a MySQL database using PHP? Well, you have found the best tutorial. Here you will learn it with simple steps & standard source code. All the steps will be very simple to understand & lean. Even you can easily integrate it into your projects.

Generally, Developers upload a single file at a time. But Sometimes you need to upload multiple files at a time. So, PHP provides the best functionality to implement it. So that you can easily upload files to the server folder and can store file names in the MySQL database. Even you can display the uploaded files on the web page. All these tasks are shared step by step.

After reading this tutorial, You will be able to upload different types of file extensions like jpg, gif, png, pdf, doc, zip, CSV & more. You will get the option to allow required file extensions. Only allowed file extensions will be uploaded.

upload multiple files in php

Upload Multiple Files and Store in MySQL Database Using PHP

As you know that you have to use file Input Filed to upload the files. So, for uploading multiple files, You will have to click on the file browse button. Even you have to select multiple files by pressing the ctrl or shift key. then click the submit button.

Read Also 

How to Insert Data Using Ajax in PHP and MySQL

upload multiple files at a time using PHP

How to create pagination in PHP and MySQL

Now, I am going to explain the multiple file upload script through the following steps

Before going to the next step, you should create the following folder structure

myproject/
   |__uploads/
   |__database.php
   |__upload-form.php
   |__upload-script.php
   |__display-files.php

1. Create a MySQL Database & table

I have created a database codingstatus  and connect to PHP using the following query.

<?php 
$hostname     = "localhost";
$username     = "root";
$password     = ""; 
$databasename = "codingstatus"; 
// Create connection 
$conn = new mysqli($hostname, $username, $password,$databasename);
 // Check connection 
if ($conn->connect_error) { 
die("Unable to Connect database: " . $conn->connect_error);
 }
?>

I have also  created a table files . You can create it according to your project requirement.

CREATE TABLE `files` (
  `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `file_name` varchar(255) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2.  Create a form to upload multiple files

  • Include upload-script.php
  • Create a form with two attributes
    • method=”post”
    • enctype=”multipart/form-data”
  • Create a file input with three attribute
    • type=”file”
    • name=”file_name[]”
    • multiple
  • Create a submit button with name=”submit”

File Name – upload-form.php

<?php include('upload-script.php'); ?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="upload-form">
<form  method="post" enctype="multipart/form-data">
    <input type="file" name="file_name[]" multiple>
    <input type="submit" value="Upload File" name="submit">
</form>
</div>
</body>
</html>

To upload files, you must declare the following attribute.

S.N Attribute & name  Usage
 1 method=”post” It sends input data with security
 2 enctype=”multipart/form-data”  It allows uploading different types of files
 3 name=”file_name[]”  It can access multiple files in an array
 3 multiple  It allows us to select multiple files from the local computer.

Now, you will write the code from the next step no 3 to 6 in upload-script.php. In these steps, you will get the script to upload, store, fetch & display multiple files.

3. Write PHP code to upload Multiple in MySQL Database

include your database connection database.php. The event put your connection variable & table name to the given variable

Check the input values are set or not on submitting the form. if it is set then call the user-defined function upload-files($tableName) to upload the files to the server. Where $tableName is passed as a parameter?. It will accept the Table name in which the filename will be stored.

Declare user-defined function upload-files($tableName). When multiple files will be uploaded successfully,

It will call another user-defined function store-files($storeFilesBasename,$tableName). Where $storeFilesBasename will pass multiple files name with extensions to store in the database table.

Now, declare the user-defined function store-files($storeFilesBasename, $tableName). This function will store multiple files name with extensions in the database table.

If you want to fetch files from the database table, you can write the following scripts within a user-defined function fetch-files($tableName).

This function will return the files’ names in the array value. you can display the files on the web page by using this array value with foreach loop.

Call fetch-files($tableName) and assign it to a variable. you can use this variable with foreach a loop to display files on the web page.

File Name – upload-script.php

<?php 
require_once('database.php');

$db=$conn; // Enter your Connection variable;
$tableName='files'; // Enter your table Name;

// fetching files from database
$fetchFiles=fetch_files($tableName);

// uploading files on submit
if(isset($_POST['submit'])){ 

    //  uploading files
    echo upload_files($tableName); 
}



  function upload_files($tableName){
   
    $uploadTo = "uploads/"; 
    $allowFileExt = array('jpg','png','jpeg','gif','pdf','doc','csv','zip');
    $fileName = array_filter($_FILES['file_name']['name']);
    $fileTempName=$_FILES["file_name"]["tmp_name"];
    $tableName= trim($tableName);
    if(empty($fileName)){ 
       $error="Please Select files..";
       return $error;
     }else if(empty($tableName)){
       $error="You must declare table name";
       return $error;
     }else{
    
     $error=$storeFilesBasename='';

    foreach($fileName as $index=>$file){
         
    $fileBasename = basename($fileName[$index]);
    $filePath = $uploadTo.$fileBasename; 
    $fileExt = pathinfo($filePath, PATHINFO_EXTENSION); 

    if(in_array($fileExt, $allowFileExt)){ 

        // Upload file to server 
        if(move_uploaded_file($fileTempName[$index],$filePath)){ 
        
         // Store Files into database table
         $storeFilesBasename .= "('".$fileBasename."'),"; 
          
         }else{ 
         $error = 'File Not uploaded ! try again';

         } 

     }else{

       $error .= $_FILES['file_name']['name'][$index].' - file extensions not allowed<br> ';

     }
    }

    store_files($storeFilesBasename, $tableName);
  }

    return $error;
}
    // File upload configuration 

    function store_files($storeFilesBasename, $tableName){
      global $db;
      if(!empty($storeFilesBasename))
      {
      $value = trim($storeFilesBasename, ',');


       $store="INSERT INTO ".$tableName." (file_name) VALUES".$value;

      
      $exec= $db->query($store);
       if($exec){
       
        echo "files are uploaded successfully";
         
       }else{
        echo  "Error: " .  $store . "<br>" . $db->error;
       }
      }
    }
   
      
      // fetching padination data
function fetch_files($tableName){
   global $db;
   $tableName= trim($tableName);
   if(!empty($tableName)){
  $query = "SELECT * FROM ".$tableName." ORDER BY id DESC";
  $result = $db->query($query);

if ($result->num_rows > 0) {
    $row= $result->fetch_all(MYSQLI_ASSOC);
    return $row;       
  }else{
    
    echo "No files are stored in database";
  }
}else{
  echo "you must declare table name to fetch files";
}
}   
    
?>

6. Display Multiple Files On the web Page

  • First of all, Include upload-script.php
  • display all files on an HTML page to fetch from the MySQL database

File Name – display-files.php

<?php
include('upload-script.php');

?>

<!DOCTYPE html>
<html>
<body>

<?php
if(!empty($fetchFiles)){
  
  foreach($fetchFiles as $fileData){
   
   $allowFileExt = array('jpg','png','jpeg','gif');
      $fileExt = pathinfo($fileData['file_name'], PATHINFO_EXTENSION); 
$fileURL='uploads/'.$fileData['file_name'];
 if(in_array($fileExt, $allowFileExt)){ 
    
    $imgURL='uploads/'.$fileData['file_name'];
    ?>
    <div class="images">
    <img src="<?php echo $fileURL ?>">
    </div>
    <?php
 
}else{
?>

      <div class="files">
      	<p>Download Now</p>
       <a href='<?php echo $fileURL ?>'><?php echo $fileExt; ?></a>
   </div>
  
  <?php
}
 }


 }

?>
<!--display files from databse-->
</body>
</html>

This file contains the CSS code to customize your multiple files form & file gallery.

File Name- style.css

.files{
float: left;
  background: #efefef;
  width: 355px;
  height: 209px;
  text-align: center;
  position: relative;
  border: 5px solid #dbd6d6;
  margin: 0px 5px;
}
.files a{
color: black;
  font-size: 52px;
}
.files p{
  margin-top:38px;
}
.images img{
  width: 355px;
  height: 200px;
}
.images{
  float: left;
  border: 5px solid #dbd6d6;
  margin: 5px;
}
.upload-form{
  width: 40%;
  background: #dbd6d6;
  height: 150px;
  margin:20px;
  text-align: center;
  position: relative;
  left: 18%
}

.upload-form input[type="file"]{
border: 1px solid white;
  line-height: 20px;
  position: relative;
  top: 62px;
  padding: 6px;
}
.upload-form input[type="submit"]{
position: relative;
  top: 62px;
  background: #8f8d8d;
  border: 0px;
  padding: 10px;
  color: white;
  font-weight: bold;
}

 

Suggestion

I hope you like this tutorial. Even it is useful for you. So, Don’t forget to share with friends those who want to learn it.

If you have any queries, you can ask me through the below comment box. I will also share more coding tutorials. So you should continue to visit my blog for becoming an expert in the coding field.

 

Categories PHP

Leave a Comment