AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home PHP and MySQL

Upload Multiple Images and Store in Database using PHP and MySQL

Create Database Table

Lakshika Mathur by Lakshika Mathur
December 21, 2019
Reading Time: 5 mins read
0
Upload Multiple Images and Store in Database using PHP and MySQL

The most used function for the web application is File upload in PHP. Therefore, a single file or several files can be easily uploaded using PHP. PHP offers a fast and straightforward way to implement server-side file upload functionality. Firstly, in the web application, the file is uploaded to the server. Secondly, store the file name in the database. And at last, the files are retrieved from the server based on the file name stored in the database. In most circumstances, a single image is uploaded at once. But sometimes, you need to upload multiple images at once. In this tutorial, we will explain to you how to upload multiple images in PHP and store the photos in the MySQL database. Numerous image upload permits the user to select multiple files at once and upload all files to the server in a single click.

RELATED POSTS

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

In our example code, we will implement the following functionality to determine the multiple images upload in PHP.

  • HTML form to select multiple images.
  • By using server PHP, upload the image.
  • Store file names in the database using PHP and MySQL.
  • Retrieve images from the database and show them on the web page.

Create Database Table

We need to create a table in the database to store the image file names. The following SQL generates an image table with some required fields in the MySQL database.

CREATE TABLE `images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `uploaded_on` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

We have to use the  dbConfig.php  file to connect and select the MySQL database. Specify the database hostname ($dbHost), password ($dbPassword), username ($dbUsername) and name  ($dbName)) as per your MySQL credentials.

<?php
// Database configuration
$dbHost     = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName     = "allsweb";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

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

File Upload Form HTML

Create an HTML form with an input field to permit the user to select images they want to upload.

The <form> tag must contain the following attributes.

  • method=”post”
  • enctype=”multipart/form-data”

The <input> tag must contain type=”file” and multiple attributes.

<form action="" method="post" enctype="multipart/form-data">
    Select Image Files to Upload:
    <input type="file" name="files[]" multiple >
    <input type="submit" name="submit" value="UPLOAD">
</form>

SEE ALSO: Upload and Add Watermark to Image using PHP

Upload Multiple Files in PHP (upload.php)

The upload.php file handles the multiple-image upload functionality and shows the upload status to the user.

  • Attach the database configuration file to connect and select the MySQL database.
  • Get the file extension using pathinfo() function in PHP and check whether the user selects only the image files.
  • Upload images to the server using move_uploaded_file() function in PHP.
  • Insert image file names in the database using PHP and MySQL.
  • Show the upload status to the user.
<?php
if(isset($_POST['submit'])){
    // Include the database configuration file
    include_once 'dbConfig.php';
    
    // File upload configuration
    $targetDir = "uploads/";
    $allowTypes = array('jpg','png','jpeg','gif');
    
    $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadType = '';
    if(!empty(array_filter($_FILES['files']['name']))){
        foreach($_FILES['files']['name'] as $key=>$val){
            // File upload path
            $fileName = basename($_FILES['files']['name'][$key]);
            $targetFilePath = $targetDir . $fileName;
            
            // Check whether file type is valid
            $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
            if(in_array($fileType, $allowTypes)){
                // Upload file to server
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFilePath)){
                    // Image db insert sql
                    $insertValuesSQL .= "('".$fileName."', NOW()),";
                }else{
                    $errorUpload .= $_FILES['files']['name'][$key].', ';
                }
            }else{
                $errorUploadType .= $_FILES['files']['name'][$key].', ';
            }
        }
        
        if(!empty($insertValuesSQL)){
            $insertValuesSQL = trim($insertValuesSQL,',');
            // Insert image file name into database
            $insert = $db->query("INSERT INTO images (file_name, uploaded_on) VALUES $insertValuesSQL");
            if($insert){
                $errorUpload = !empty($errorUpload)?'Upload Error: '.$errorUpload:'';
                $errorUploadType = !empty($errorUploadType)?'File Type Error: '.$errorUploadType:'';
                $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUploadType:'<br/>'.$errorUploadType;
                $statusMsg = "Files are uploaded successfully.".$errorMsg;
            }else{
                $statusMsg = "Sorry, there was an error uploading your file.";
            }
        }
    }else{
        $statusMsg = 'Please select a file to upload.';
    }
    
    // Display status message
    echo $statusMsg;
}
?>

SEE ALSO: Radius Based Location Search with PHP and MySQL

Display Images from Database

Initially, we will retrieve the file names from the database and display the images related to the server on the web page.

  • Firstly, include the database configuration file to connect and select the MySQL database.
  • Secondly, fetch images from the MySQL database using PHP.
  • Finally, retrieve images from the server (upload /) and list them on the web page.
<?php
// Include the database configuration file
include_once 'dbConfig.php';

// Get images from the database
$query = $db->query("SELECT * FROM images ORDER BY id DESC");

if($query->num_rows > 0){
    while($row = $query->fetch_assoc()){
        $imageURL = 'uploads/'.$row["file_name"];
?>
    <img src="<?php echo $imageURL; ?>" alt="" />
<?php }
}else{ ?>
    <p>No image(s) found...</p>
<?php } ?>

Conclusion

Firstly, in this tutorial, we have explained to you the easiest way to integrate multiple images upload functionality on the website. Secondly, You can also use this example code to upload multiple files in PHP. At last, you can spread these multiple images to upload feature as per your need. 

Also, read our previous blog- Ajax File Upload using jQuery and PHP

Tags: Multiple ImagesPHP and MySQL
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

What is Application Programming Interface (APIs), Types, and Importance.
PHP and MySQL

What is Application Programming Interface (APIs)?

January 29, 2022
61
Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
739
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
162
How to Force Download File in PHP
PHP and MySQL

How to Force Download File in PHP

January 2, 2020
82
How to Connect to the Remote MySQL Database using PHP
PHP and MySQL

How to Connect to the Remote MySQL Database using PHP

January 1, 2020
28
How to Generate QR Code with PHP using Google Chart API
PHP and MySQL

How to Generate QR Code with PHP using Google Chart API

January 1, 2020
83
Next Post
Create a Dynamic Image with PHP

Dynamic Image Creation with PHP

Preview and Rotate Image Before Upload using jQuery and PHP

Preview and Rotate Image Before Upload using jQuery and PHP

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version