Upload Multiple Image files to the Database using PDO – PHP

You can store the image files in the Database table either in base64 format or its path after uploading.

In the base64 method, it is not necessary to store the uploaded file on the server because it is been directly accessed with the base64 encoded value.

In this tutorial, I am using PDO connection for storing multiple image files path in the MySQL database table.

Upload Multiple Image files to the Database using PDO – PHP


  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. Conclusion

1. Table structure

I am using images table for storing data.

CREATE TABLE `images` (
  `name` varchar(80) NOT NULL,
  `image` varchar(80) NOT NULL

2. Configuration

Create a config.php file for the database connection.

Completed Code

$server = "localhost";
$username = "root";
$password = "";
$dbname = "tutorial";

// Create connection
  $conn = new PDO("mysql:host=$server;dbname=$dbname","$username","$password");
}catch(PDOException $e){
  die('Unable to connect with the database');


Create a <form> within this add a file element and a submit button. To enable selecting multiple files define multiple attribute in file element.

Completed Code

<form method='post' action='' enctype='multipart/form-data'>
  <input type='file' name='files[]' multiple />
  <input type='submit' value='Submit' name='submit' />

4. PHP

Create an upload folder for storing the image files.

On the submit button click count total selected files and create a prepared statement for inserting the record in the images table.

Loop on the files and extract the extension to check file is an image or not.

If it is image file then store it in upload folder and execute the statement using execute() method that pass an array while contains file name and path.

Completed Code

include "config.php";

  // Count total files
  $countfiles = count($_FILES['files']['name']);
  // Prepared statement
  $query = "INSERT INTO images (name,image) VALUES(?,?)";

  $statement = $conn->prepare($query);

  // Loop all files

    // File name
    $filename = $_FILES['files']['name'][$i];

    // Location
    $target_file = 'upload/'.$filename;

    // file extension
    $file_extension = pathinfo($target_file, PATHINFO_EXTENSION);
    $file_extension = strtolower($file_extension);

    // Valid image extension
    $valid_extension = array("png","jpeg","jpg");

    if(in_array($file_extension, $valid_extension)){

       // Upload file

          // Execute query

  echo "File upload successfully";

5. Conclusion

In the demonstration, I stored the uploaded image files path in the MySQL database table when the file successfully uploaded but you can also store the file in the base64 format in the field.

If you found this tutorial helpful then don't forget to share.