PHP 8 Multiple Files/Images Upload in MySQL Database

03-Apr-2023

.

Admin

Hi Guys,

In this tutorial,I will learn you how to multiple image and file upload in mysql database using php 8.you can easy and simply multiple image and file upload in mysql database using php 8.

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

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.

$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>

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>

It will help you...

#PHP 8

#PHP