Bigginers

How to Upload Multiple Images and Store in Database using PHP, MySQL

Pinterest LinkedIn Tumblr

Uploading images or files is the functionality that is mostly used in web applications. In most cases, we upload a single image or file like a profile picture, pdf file or anything else. In this tutorial, you will learn How to Upload Multiple Images in PHP step by step. Check our demo.

But when it comes to uploading multiple images or files we need to think some logic and process how to do that. But sometimes you have a requirement to upload multiple images at once.

Generally, in the web application, the file/image is uploaded to the folder of the server and the file name is stored in the database. Later the files are fetched from the folder based on the file name stored in the database.  

In this tutorial, we will implement all these processes, step by step.

  • 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

Create a database table

First, we need to make a database table to store the names of images we will upload. As we know earlier, Images are stored in the folder of the server and the name is saved to database tables.

Create two columns named ID and imgName with ID to be auto-incremented. I hope you know how to create tables in the database.

Create an image/file uploading form

  <form action="upload-script.php" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <div class="row">
               <div class="col-md-4">
                   <div class="form-group">
                       <input type="file" name="imageFile[]" required multiple class="form-control">
                   </div>
               </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <input type="submit" name="uploadImageBtn" id="uploadImageBtn" value="Upload Images" class="btn btn-success">
                    </div>
                </div>
            </div>
        </div>
    </form>

If you see in this <form> tag, I used the action to upload-script.php. This is the logic file to upload multiple images. And name=”imageFile[]”, there are square braces that indicate an array of images.

The database connection file

<?php
$hostName = "localhost"; // host name
$username = "root";  // database username
$password = ""; // database password
$databaseName = "codingbirds"; // database name

$connection = new mysqli($hostName,$username,$password,$databaseName);
if (!$connection) {
    die("Error in database connection". $connection->connect_error);
}
?>

This is the connection file to the database. There are hostname, username, password and database name. You can change accordingly.

The image uploads the logic script file

upload-script.php

<?php
include "config.php";
if (isset($_POST['uploadImageBtn'])) {
    $uploadFolder = 'uploads/';
    foreach ($_FILES['imageFile']['tmp_name'] as $key => $image) {
        $imageTmpName = $_FILES['imageFile']['tmp_name'][$key];
        $imageName = $_FILES['imageFile']['name'][$key];
        $result = move_uploaded_file($imageTmpName,$uploadFolder.$imageName);

        // save to database
        $query = "INSERT INTO bird_multiple_images SET imgName='$imageName' " ;
        $run = $connection->query($query) or die("Error in saving image".$connection->error);
    }
    if ($result) {
        echo '<script>alert("Images uploaded successfully !")</script>';
        echo '<script>window.location.href="index.php";</script>';
    }
}

This code has a foreach loop to upload multiple images and uploads them into a folder named “uploads”. And finally saves the name of the images to the database.

Display Images from Database

This is the code to fetch images from the database and display it in a row-column format.

 <?php
// fetch Images
$i = 1;
include "config.php";
$queryGetImg = "SELECT * FROM bird_multiple_images";
$resultImg = $connection->query($queryGetImg);
if ($resultImg->num_rows > 0 ){
  while ($row = $resultImg->fetch_object()){ ?>
     <div class="col-sm-3">
	<h3>Image <?php echo $i;?></h3>
	<img src="<?php echo 'uploads/'.$row->imgName;?>"/>
    </div>
    <?php $i++;
   }
}
?>

Complete Code for How to Upload Multiple Images

Here is the complete code that includes all the steps told above. I separated the code so that you can understand properly. Now following is the complete code for you.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Upload Multiple Images with PHP</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
</head>
<body>
<div class="jumbotron text-center">
    <h1>Upload Multiple Images with PHP</h1>
    <p>Resize this responsive page to see the effect!</p>
</div>
<div class="container">
    <form action="upload-script.php" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <div class="row">
               <div class="col-md-4">
                   <div class="form-group">
                       <input type="file" name="imageFile[]" required multiple class="form-control">
                   </div>
               </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <input type="submit" name="uploadImageBtn" id="uploadImageBtn" value="Upload Images" class="btn btn-success">
                    </div>
                </div>
            </div>
        </div>
    </form>

    <div class="row">
        <?php
        // fetch Images
        $i = 1;
        include "config.php";
        $queryGetImg = "SELECT * FROM bird_multiple_images";
        $resultImg = $connection->query($queryGetImg);
        if ($resultImg->num_rows > 0 ){
            while ($row = $resultImg->fetch_object()){ ?>
                <div class="col-sm-3">
                    <h3>Image <?php echo $i;?></h3>
                    <img src="<?php echo 'uploads/'.$row->imgName;?>"/>
                </div>
           <?php $i++;
            }
        }
        ?>
    </div>
</div>
</body>
</html>

If you face any errors in coding, then you can comment and I will surely help. And you can download the source code from here.

You can watch the video also on my YouTube channel named KanpurWebD and make sure you subscribe also.

 

Happy Coding 🙂

I am a professional Web / Software developer, B.Tech CSE, who has been working in PHP & CodeIgniter and WordPress for more than 2+ years and know it inside and out, including the creation of Web Apps, WordPress websites from scratch and their customization.

Write A Comment