PHP MySQLi How To Upload Multiple Images Files Tutorial

Reading Time: 7 minutes
1,950 Views

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

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

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 – images

CREATE TABLE `images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `image_name` varchar(220) NOT NULL,
 `status` int(5) NOT NULL DEFAULT '1',
 `uploaded_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Application Folder Structure

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

Create a folder with name php-upload-multiple-images and create these 2 files into it. And also create a uploads/ folder. This is to store images. 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 Images Tutorial
 @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.

<?php
/*
 @Author: Sanjay Kumar
 @Project: PHP MySQLi How To Upload Multiple Images Tutorial
 @Email: onlinewebtutorhub@gmail.com
 @Website: https://onlinewebtutorblog.com/
*/
?>

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

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>PHP MySQLi How To Upload Multiple Images</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>

<body>
    <?php
    // Include the database configuration file 
    include "dbconfig.php";

    if (isset($_POST['submit'])) {

        $targetDir = "uploads/";

        $allowTypes = array('jpg', 'png', 'jpeg', 'gif');

        $images_arr = array();

        foreach ($_FILES['images']['name'] as $key => $val) {

            $image_name = $_FILES['images']['name'][$key];
            $tmp_name = $_FILES['images']['tmp_name'][$key];
            $size = $_FILES['images']['size'][$key];
            $type = $_FILES['images']['type'][$key];
            $error = $_FILES['images']['error'][$key];

            $fileName = basename($_FILES['images']['name'][$key]);
            $targetFilePath = $fileName;

            $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);

            if (in_array($fileType, $allowTypes)) {

                if (move_uploaded_file($_FILES['images']['tmp_name'][$key], $targetDir . $targetFilePath)) {

                    $images_arr[] = $targetFilePath;

                    $stmt = $conn->prepare("INSERT INTO images (image_name) VALUES (?)");
                    $stmt->bind_param("s", $imagePath);

                    $imagePath = $targetDir . $targetFilePath;

                    $stmt->execute();
                } else {
                    $statusMsg = "Sorry, there was an error uploading your file.";
                }
            } else {
                $statusMsg = 'Please Upload a Valid File';
            }
        }

        if (count($images_arr) > 0) {
            $success = count($images_arr) . " Image files successfully uploaded";
        }
    }
    ?>

    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card w-75 m-auto">
                    <div class="card-header text-center bg-primary text-white">
                        <h4>PHP MySQLi How To Upload Multiple Images</h4>
                    </div>
                    <div class="card-body">
                        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

                            <?php if (!empty($success)) { ?>
                                <p class="alert alert-success"><?php echo $success; ?></p>
                            <?php } ?>

                            <div class="form-group">
                                <div class="custom-file">
                                    <label><strong>Select Images : <span class="text-danger">*</span></strong></label>
                                    <input type="file" name="images[]" id="customFile" class="form-control" multiple required>
                                </div>

                                <?php if (!empty($statusMsg)) { ?>
                                    <p class="text-danger"><?php echo $statusMsg; ?></p>
                                <?php } ?>

                            </div>

                            <br>
                            <div class="form-group d-flex">
                                <input type="submit" name="submit" value="Upload" class="btn btn-success rounded-0 px-3">
                            </div>

                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

Application Testing

Now,

URL: http://localhost/php-upload-multiple-images/index.php

Upload form

Select Image and Upload

You should see inside database table, records as –

The image files will be uploaded to uploads/ directory.

Download Complete Source Code

We hope this article helped you to PHP MySQLi How To Upload Multiple Images Files 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