PHP MySQLi How to Upload Multiple Files with Ajax

Reading Time: 7 minutes
1,270 Views

Inside this article we will see the concept i.e PHP MySQLi How to Upload Multiple Files with Ajax in database. Tutorial contains the classified information about uploading multiple files in PHP. We will use mysqli connection for database connectivity and operations.

If you are looking for an article to understand the multiple files upload process then this article will be super easy to understand. This will give you the complete idea about uploading multiple files and save inside PHP MySQLi.

Files are of type – txt, pdf, docx, csv, xlsx means also we add type validation using jquery.

Learn More –

Let’s get started.

Create Database & Table

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE php_applications;

Inside this database, we need to create a table.

Table we need – files

CREATE TABLE `files` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(255) NOT NULL,
 `uploaded_on` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Application Folder Structure

You need to create a folder structure to develop this application in PHP and MySQLi. Have a look the files and folder inside this application –

Create a folder with name php-mysqli-ajax-upload-multiple-files and create these 4 files into it. And also create a uploads/ folder. This is to store files. Make sure this folder should have sufficient permission to read and write files into it.

Database Configuration

Open dbconfig.php file from folder. Add these lines of code into it.

<?php
/*
 @Author: Sanjay Kumar
 @Project: PHP MySQLi How to Upload Multiple Files with Ajax
 @Email: onlinewebtutorhub@gmail.com
 @Website: https://onlinewebtutorblog.com/
*/

// Database configuration
$host   = "localhost";
$dbuser = "admin";
$dbpass = "Admin@123";
$dbname = "php_applications";

// Create database connection
$conn = new mysqli($host, $dbuser, $dbpass, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

Application Programming

Open index.php file and write this following code into it. This file is to create upload files frontend layout. Also it contains the link to script.js.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>PHP MySQLi How to Upload Multiple Files with Ajax</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card m-auto w-75">
                    <div class="card-header text-center text-white bg-primary">
                        <h4>PHP MySQLi How to Upload Multiple Files with Ajax</h4>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-success alert-dismissible" id="success" style="display: none;">
                            <button type="button" class="close" data-dismiss="alert">×</button>
                            File uploaded successfully
                        </div>
                        <form id="submitForm">
                            <div class="form-group">
                                <label><strong>Select Files : </strong><span class="text-danger"> *</span></label>
                                <input type="file" class="form-control" name="multipleFile[]" id="multipleFile" multiple>
                                <span id="error" class="text-danger"></span><br>
                            </div>
                            <div class="form-group d-flex">
                                <button type="submit" name="upload" class="btn btn-primary">Upload</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="script.js"></script>
</body>

</html>

Ajax Script Code

Open script.js file from folder. This file used to trigger ajax request. Also this file validates file type when file uploads.

/*
 @Author: Sanjay Kumar
 @Project: PHP MySQLi How to Upload Multiple Files with Ajax
 @Email: onlinewebtutorhub@gmail.com
 @Website: https://onlinewebtutorblog.com/
*/

$(document).ready(function() {

    $("input").prop('required', true);

    $('#multipleFile').change(function() {
        var ext = this.value.match(/\.(.+)$/)[1];
        switch (ext) {
            case 'txt':
            case 'pdf':
            case 'docx':
            case 'csv':
            case 'xlsx':
                $('#error').text("");
                $('button').attr('disabled', false);
                break;
            default:
                $('#error').text("File must be of type txt,pdf,docx,csv,xlsx.");
                $('button').attr('disabled', true);
                this.value = '';
        }
    });

    $("#submitForm").on("submit", function(e) {
        e.preventDefault();
        $.ajax({
            url: "process.php",
            type: "POST",
            cache: false,
            contentType: false, // you can also use multipart/form-data replace of false
            processData: false,
            data: new FormData(this),
            success: function(response) {
                $("#success").show();
                $("#success").fadeOut(2800);
            }
        });
    });
});

Ajax Handler – Upload Files

Open process.php file from application. Write these lines of code into it.

<?php
/*
 @Author: Sanjay Kumar
 @Project: PHP MySQLi How to Upload Multiple Files with Ajax
 @Email: onlinewebtutorhub@gmail.com
 @Website: https://onlinewebtutorblog.com/
*/

// Include the database configuration file 
include "dbconfig.php";

if (!empty($_FILES['multipleFile']['name'])) {

    $multiplefile = $_FILES['multipleFile']['name'];

    foreach ($multiplefile as $name => $value) {

        $allowFile = array('txt', 'pdf', 'docx', 'csv', 'xlsx');

        $fileExnt = explode('.', $multiplefile[$name]);

        if (in_array($fileExnt[1], $allowFile)) {

            if ($_FILES['multipleFile']['size'][$name] > 0 && $_FILES['multipleFile']['error'][$name] == 0) {

                $fileTmp = $_FILES['multipleFile']['tmp_name'][$name];

                $newFile =  rand() . '.' . $fileExnt[1];
                $target_dir = 'uploads/' . $newFile;

                if (move_uploaded_file($fileTmp, $target_dir)) {

                    $stmt = $conn->prepare("INSERT INTO files (file_name) VALUES (?)");
                    $stmt->bind_param("s", $target_dir);

                    $stmt->execute();
                }
            }
        }
    }
}

Application Testing

Now,

URL: http://localhost/php-mysqli-ajax-upload-multiple-files/index.php

Upload Files Form

When files saved inside database, records be like –

Download Complete Source Code

We hope this article helped you to learn PHP MySQLi How to Upload Multiple Files with Ajax Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more