Upload Multiple Files in MySQL Database Using PHP

Do 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 straightforward to understand & learn. 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 you have to use the 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.

You should also learn the following examples –

1. Create a Folder Structure

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

myproject/
   |__public/images/
   |__database.php
   |__index.php
   |__script.php
   |__gallery.php
   |__style.css

1. Create a MySQL Database & table

You can create a table with the name ‘file’ in the PhpMyAdmin as the given query below.

Database Name – codingstatus

Table Name – files

CREATE TABLE `files` (
  `id` int(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `file_name` varchar(255) DEFAULT NULL,
)

2.  Connect to MySQL Database

Now, You have to connect PHP to the MySQL database using the following code

Where –

  • $hostname: assign to it your database hostname.
  • $username: assign to it your database username
  • $password: assign to it your database password

File Name – database.php

<?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);
 }
?>

3. Create a form to upload Files

This code sets up a simple HTML form with a file input field, allowing users to select and upload one or more files. The actual handling of the file upload is expected to be implemented in the ‘upload-script.php’ file, which is included at the beginning of the code.

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>

Explanation –

  • Include the ‘upload-script.php’ file, likely containing code to handle file uploads.
  • Initiate an HTML form with POST method and multipart/form-data encoding for file uploads.
  • Create a file input field allowing users to select and upload multiple files, with the name “file_name[]”.
  • Adds a submit button labeled “Upload File” to trigger form submission.

4. Upload Multiple files script

This PHP code manages file upload functionality, connecting to a database, uploading files to a designated folder, and storing file names in a specified table.

File Name – 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";
}
}   
    
?>

Explanation –

  • The PHP code establishes a database connection and sets the table name for file storage.
  • It fetches files from the specified database table using the fetch_files function.
  • Upon form submission ($_POST['submit']), the code attempts to upload selected files to a designated folder and inserts their names into the database.
  • The upload_files function handles file uploading, checks allowed file extensions, and outputs error messages if any issues occur.
  • The store_files function inserts file names into the specified database table.
  • Pagination data for the files is retrieved using the fetch_files function, ordered by ID in descending order.

5. Display Multiple uploaded Files

This HTML document includes an external PHP script for file upload and database interactions. It dynamically displays images and downloadable files fetched from the database, categorizing them based on allowed extensions.

File Name – gallery.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>

Explanation –

  • The code includes an external script (upload-script.php) that manages file uploading and database interactions.
  • The HTML document displays files fetched from the database, categorizing them as images or downloadable files based on allowed extensions.
  • For images, it generates <img> tags with the corresponding file URLs; for other files, it provides download links.
  • The file data is obtained from the $fetchFiles array, which is populated by the fetch_files function in the included script.

6. Design Files Gallary

You can also use the following CSS to design the 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;
}