Multiple image upload in php mysqli

Home  »  MySQL • PHP   »   PHP 8 Multiple Files/Images Upload in MySQL Database

This is a comprehensive PHP 8 Multiple Files and Images uploading tutorial, learn to store image files in the MySQL database along with some necessary file uploading validation.

File upload in PHP is the most common feature that almost every PHP developer has to build. As we can know, file uploading functionality is required in nearly every web application. Be it Instagram, Twitter, Facebook or Tumblr a user can’t live without uploading files nowadays.

In this tutorial, we will learn how to upload single or multiple files or images in PHP 8 and how to save the images in MySQL database. We will also cover the necessary file uploading validation using the PHP methods and API.

Usually, a user tends to upload a single image and store the image on the database using the file name. This way, we can also fetch the image or file from the database using the file name. Sometimes, based on some specific requirements, we have to upload Multiple images or files on the server.

Tutorial Objective

By the end of this tutorial, you will be able to understand the following concepts:

  • Create an HTML form to select multiple images and files.
  • Display multiple images preview before sending to server.
  • Implement necessary validation before uploading.
  • Save files in the local directory and store the uploaded file path in the database.

Project Files Structure

We are following the given below files and folder structure to upload multiple files in PHP 8.

\-- php-multiple-file-upload
  |-- config
      |--- database.php
  |-- uploads
      |--- image-1
      |--- image-2
      |--- image-3
  |-- file-upload.php
  |-- index.php

Table Configuration in Database

You can use MAMP or XAMPP to create database and table for multiple file uploading in PHP.

Create database `database_name`.

Create `table_name` inside the database.

Run the following SQL script from the PHPMyAdmin panel to create user tables, and it will have an id, images, and data_time values in the MySQL database.

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `images` varchar(255) NOT NULL,
  `date_time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Connect PHP Project with MySQL

To make the connection between the database and PHP project, we defined the database connection with the PDO approach and kept the db configuration in the config/database.php file.

<?php
    $hostname = "localhost";
    $username = "root";
    $password = "";
    try {
        $conn = new PDO("mysql:host=$hostname;dbname=php_crud", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //echo "Database connected successfully";
    } catch(PDOException $e) {
        echo "Database connection failed: " . $e->getMessage();
    }
?>

Create File Upload Form with HTML and Bootstrap 4

To create the file upload form we are using Bootstrap 4, add the Bootstrap CDN link in between the head tag.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

Create a simple file upload form using HTML form tag, the form tag must contain the method=”post” and enctype=”multipart/form-data” tags.

To make it interact with PHP APIs, do define the name=”fileUpload[]” tag with an input form field. By default, the HTML file field allows a single file to upload. Pass the multiple tag with a file input field to choose multiple files at once.

<form action="" method="post" enctype="multipart/form-data" class="mb-3">
  <div class="custom-file">
    <input type="file" name="fileUpload[]" class="custom-file-input" id="chooseFile" multiple>
    <label class="custom-file-label" for="chooseFile">Select file</label>
  </div>
  <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
    Upload Files
  </button>
</form>

Display Multiple Files Preview

A user must know which files he is going to put on the server, create a html div inside the files upload form.

<div class="imgGallery">
  <!-- image preview -->
</div>

We need to place the jQuery link in the footer and also place the following JavaScript code that shows the preview of all the user selected files.

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script>
  $(function () {
    // Multiple images preview with JavaScript
    var multiImgPreview = function (input, imgPreviewPlaceholder) {
      if (input.files) {
        var filesAmount = input.files.length;
        for (i = 0; i < filesAmount; i++) {
          var reader = new FileReader();
          reader.onload = function (event) {
            $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
          }
          reader.readAsDataURL(input.files[i]);
        }
      }
    };
    $('#chooseFile').on('change', function () {
      multiImgPreview(this, 'div.imgGallery');
    });
  });
</script>

Multiple image upload in php mysqli

Upload Multiple Files in PHP 8 with Validation

We define the multiple file uploading code in the file-upload.php file and alert the user about the file upload activity.

<?php 
    // Database
    include 'config/database.php'; 
    if(isset($_POST['submit'])){
        
        $uploadsDir = "uploads/";
        $allowedFileType = array('jpg','png','jpeg');
        
        // Velidate if files exist
        if (!empty(array_filter($_FILES['fileUpload']['name']))) {
            
            // Loop through file items
            foreach($_FILES['fileUpload']['name'] as $id=>$val){
                // Get files upload path
                $fileName        = $_FILES['fileUpload']['name'][$id];
                $tempLocation    = $_FILES['fileUpload']['tmp_name'][$id];
                $targetFilePath  = $uploadsDir . $fileName;
                $fileType        = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
                $uploadDate      = date('Y-m-d H:i:s');
                $uploadOk = 1;
                if(in_array($fileType, $allowedFileType)){
                        if(move_uploaded_file($tempLocation, $targetFilePath)){
                            $sqlVal = "('".$fileName."', '".$uploadDate."')";
                        } else {
                            $response = array(
                                "status" => "alert-danger",
                                "message" => "File coud not be uploaded."
                            );
                        }
                    
                } else {
                    $response = array(
                        "status" => "alert-danger",
                        "message" => "Only .jpg, .jpeg and .png file formats allowed."
                    );
                }
                // Add into MySQL database
                if(!empty($sqlVal)) {
                    $insert = $conn->query("INSERT INTO user (images, date_time) VALUES $sqlVal");
                    if($insert) {
                        $response = array(
                            "status" => "alert-success",
                            "message" => "Files successfully uploaded."
                        );
                    } else {
                        $response = array(
                            "status" => "alert-danger",
                            "message" => "Files coudn't be uploaded due to database error."
                        );
                    }
                }
            }
        } else {
            // Error
            $response = array(
                "status" => "alert-danger",
                "message" => "Please select a file to upload."
            );
        }
    } 
?>

Add the database connection file to run the SQL query to make the interaction with the database.

Add the validation to make sure whether the images are selected, and the correct file type is chosen, and using the SQL script, insert the files into the database.

If files pass the above validation, then move all the files in the uploads directory with the help of the move_uploaded_file() method and store the images’ location path in the database.

Next, include the file-upload.php file in the form template. It allows users to select the multiple files using PHP 8 and MySQL.

<?php include("file-upload.php"); ?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <title>PHP 8 Upload Multiple Files Example</title>
  <style>
    .container {
      max-width: 450px;
    }
    .imgGallery img {
      padding: 8px;
      max-width: 100px;
    }    
  </style>
</head>
<body>
  <div class="container mt-5">
    <form action="" method="post" enctype="multipart/form-data" class="mb-3">
      <h3 class="text-center mb-5">Upload Multiple Images in PHP 8</h3>
      <div class="user-image mb-3 text-center">
        <div class="imgGallery"> 
          <!-- Image preview -->
        </div>
      </div>
      <div class="custom-file">
        <input type="file" name="fileUpload[]" class="custom-file-input" id="chooseFile" multiple>
        <label class="custom-file-label" for="chooseFile">Select file</label>
      </div>
      <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
        Upload Files
      </button>
    </form>
    <!-- Display response messages -->
    <?php if(!empty($response)) {?>
        <div class="alert <?php echo $response["status"]; ?>">
           <?php echo $response["message"]; ?>
        </div>
    <?php }?>
  </div>
  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script>
    $(function() {
    // Multiple images preview with JavaScript
    var multiImgPreview = function(input, imgPreviewPlaceholder) {
        if (input.files) {
            var filesAmount = input.files.length;
            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();
                reader.onload = function(event) {
                    $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
                }
                reader.readAsDataURL(input.files[i]);
            }
        }
    };
      $('#chooseFile').on('change', function() {
        multiImgPreview(this, 'div.imgGallery');
      });
    });    
  </script>
  
</body>
</html>

Conclusion

Finally, multiple images Upload in PHP with MySQL Database tutorial is over. We learned to implement validation for multiple files upload component in PHP.

I assume you loved this tutorial, and you can also find the full code of this tutorial on GitHub.

How can I upload multiple images at a time in PHP?

Upload Multiple Files in PHP (upload..
Include the database configuration file to connect and select the MySQL database..
Get the file extension using pathinfo() function in PHP and check whether the user selects only the image files..
Upload images to the server using move_uploaded_file() function in PHP..

How can I store multiple images in PHP?

Tutorial Objective.
Create an HTML form to select multiple images and files..
Display multiple images preview before sending to server..
Implement necessary validation before uploading..
Save files in the local directory and store the uploaded file path in the database..

How can I upload multiple images in one record in SQL?

How to Upload Multiple Images and Store in Database using PHP,....
Create a database table..
Create an image/file uploading form..
The database connection file..
The image uploads the logic script file..
Display Images from Database..
Complete Code..

How can we upload multiple files in PHP and store in database?

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”.