0% found this document useful (0 votes)
61 views

Upload Multiple Images and Store in Database Using PHP and MySQL - 07069564369

This document discusses how to upload multiple images to a server and store the file names in a MySQL database using PHP. An HTML form is created to select multiple images. PHP handles uploading the files to the server and inserting the names into the database. The images can then be retrieved and displayed by selecting the names from the database.

Uploaded by

All In One
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Upload Multiple Images and Store in Database Using PHP and MySQL - 07069564369

This document discusses how to upload multiple images to a server and store the file names in a MySQL database using PHP. An HTML form is created to select multiple images. PHP handles uploading the files to the server and inserting the names into the database. The images can then be retrieved and displayed by selecting the names from the database.

Uploaded by

All In One
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menu search
XM™ Invest in Th
Enjoy Excellent Trading Con
Commissions.

XM

HOME / PHP / UPLOAD MULTIPLE IMAGES AND STORE IN DATABASE USING PHP AND MYSQL

Upload Multiple Images and Store in Database


using PHP and MySQL
By: CodexWorld | In: PHP | Last Updated: Jun 10, 2021

Share

Upload Multiple Images and Store in Databas…


Databas…

keyboard_double_arrow_up
https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 1/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menu search

File upload in PHP is the most used functionality for the web application. A single file or multiple files
can be easily uploaded using PHP. PHP provides a quick and simple way to implement server-side file
upload functionality. Generally, in the web application, the file is uploaded to the server and the file
name is stored in the database. Later the files are retrieved from the server based on the file name
stored in the database.

In most cases, a single image is uploaded at once. But sometimes you have a requirement to upload
multiple images at once. In this tutorial, we will show you how to upload multiple images in PHP and
store the images in the MySQL database. Multiple image upload allows the user to select multiple files
at once and upload all files to the server in a single click.

Our example code will implement the following functionality to demonstrate the multiple images
upload in PHP.

HTML form to select multiple images.

Upload images to the server using PHP.

Store file names in the database using PHP and MySQL.

Retrieve images from the database and display on the web page.

Create Database Table


A table needs to be created in the database to store the image file names. The following SQL creates an
images table with some basic 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;

keyboard_double_arrow_up
Database Configuration (dbConfig.php)
https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 2/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menu
The dbConfig.php file is used to connect and select the MySQL database. Specify the database
hostname ( $dbHost ), username ( $dbUsername ), password ( $dbPassword ), and name ( $dbName ) as search
per your MySQL credentials.

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

// 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 allow 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="upload.php" 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>

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.

Include 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. keyboard_double_arrow_up
Upload images to the server using move_uploaded_file() function in PHP.

https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 3/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menu Insert image file names in the database using PHP and MySQL.

Show the upload status to the user.


search
<?php
// Include the database configuration file
include_once 'dbConfig.php';
    
if(isset($_POST['submit'])){
    // File upload configuration
    $targetDir = "uploads/";
    $allowTypes = array('jpg','png','jpeg','gif');
    
    $statusMsg = $errorMsg = $insertValuesSQL = $errorUpload = $errorUploadTyp
e = '';
    $fileNames = array_filter($_FILES['files']['name']);
    if(!empty($fileNames)){
        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], $tar
getFilePath)){
                    // Image db insert sql
                    $insertValuesSQL .= "('".$fileName."', NOW()),";
                }else{
                    $errorUpload .= $_FILES['files']['name'][$key].' | ';
                }
            }else{
                $errorUploadType .= $_FILES['files']['name'][$key].' | ';
            }
        }
        
        // Error message
        $errorUpload = !empty($errorUpload)?'Upload Error: '.trim($errorUploa
d, ' | '):'';
        $errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim
($errorUploadType, ' | '):'';
        $errorMsg = !empty($errorUpload)?'<br/>'.$errorUpload.'<br/>'.$errorUp
loadType:'<br/>'.$errorUploadType; keyboard_double_arrow_up
        

https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 4/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menu        if(!empty($insertValuesSQL)){
            $insertValuesSQL = trim($insertValuesSQL, ','); search
            // Insert image file name into database
            $insert = $db->query("INSERT INTO images (file_name, uploaded_o
n) VALUES $insertValuesSQL");
            if($insert){
                $statusMsg = "Files are uploaded successfully.".$errorMsg;
            }else{
                $statusMsg = "Sorry, there was an error uploading your file.";
            }
        }else{
            $statusMsg = "Upload failed! ".$errorMsg;
        }
    }else{
        $statusMsg = 'Please select a file to upload.';
    }
}

?>

SEE ALSO: Upload Multiple Files and Images in CodeIgniter

Display Images from Database


Now we will retrieve the file names from the database and display the respective images from the
server on the web page.

Include the database configuration file to connect and select the MySQL database.

Fetch images from MySQL database using PHP.

Retrieve images from the server (uploads/) and listed 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="" /> keyboard_double_arrow_up
<?php }

https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 5/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menu }else{ ?>
    <p>No image(s) found...</p> search
<?php } ?>

SEE ALSO: Create Dynamic Image Gallery with jQuery, PHP & MySQL

Conclusion
Here we have shown the easiest way to integrate multiple image upload functionality on the website.
This example code also is used to upload multiple files in PHP. You can extend these multiple image
upload functionality as per your needs. For user-friendly image upload, you can implement Drag and
drop file upload using Dropzone JS and PHP. Alternatively, the Ajax multiple images upload will provide
a better user-interface to the website.

file mysql php upload

Are you want to get implementation help, or modify or enhance the


functionality of this script? Click Here to Submit Service Request
If you have any questions about this script, submit it to our QA community - Ask
Question

file_download Download Source Code

arrow_back Previous Next arrow_forward


RELATED TUTORIALS keyboard_double_arrow_up
https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 6/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menu search

Upload Image to Imgur via API using PHP

Some PHP Hacks Every Programmer Should Know

keyboard_double_arrow_up
https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 7/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menu search

Login with LinkedIn using PHP

15 COMMENTS

Rudy Said...
hI Thanks,
how to randomly rename the images ?
January 28, 2023 at 12:18 PM

Shivam Maralay Said...


thanks it was simple and clear..
January 4, 2022 at 12:14 AM

Daniel Sánchez Abardía Said...


Easy and usefull code!!
Thanks!!
November 13, 2021 at 7:33 PM

Shoyo Said...
u saved my day, thank u (y)

keyboard_double_arrow_up
July 25, 2021 at 2:02 AM

Tayyab Said...

https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 8/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menuThank you very much its working


October 21, 2020 at 6:14 PM
search
Guruprasath Said...
Hi, Your code very much useful for me , Its working fine , Thank you for your wonderful
job
September 30, 2020 at 10:55 AM

Ev Said...
Hi! Thanks a lot for the code it helped me a lot and I’m just getting started with PHP. I’m
working on a hobby project and I’ve been trying to add something like a “batch id” that I
can manually input in the form upon uploading the images but I just can’t seem to get it
right, is there any other example I can look at?
Thanks a lot!
Ev.
November 24, 2019 at 9:24 PM

Meshael Said...
Kevin make user ID i.e Bob’s ID from the user table a foreign key in the image table by
adding another column. You can then get images by the user ID;
September 5, 2019 at 5:26 PM

Anshu Said...
how to fetch uploaded image in slider
August 28, 2019 at 8:47 AM

Murph Said...
Is the status column in the table necessary? I don’t see where it’s used in the rest of the
code, aside from defaulting to one if an entry is created.
August 11, 2019 at 8:03 PM

CodexWorld Said...
No, the status field is not necessary. But, it will be useful for the functionality
extension in the future.
August 12, 2019 at 4:50 PM

Kevin Said...
Your code just worked fine. Thank you. i have a question,
how if i upload 3 photo with 1 user ?
example : keyboard_double_arrow_up
https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 9/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menuname | photo
Bob | beach.jpg, home.jpg, toilet.jpg search
sorry my bad english.
June 9, 2019 at 4:44 PM

Mintu Said...
Your code just worked fine. Thank you.
May 2, 2019 at 4:46 PM

Deepak Kumar Said...


Hey, Thank you very much. I am in a hurry for my project. Your code works very smooth
in the first time of launch. Save a lot of time. Good work. Keep It up.
April 8, 2019 at 4:12 PM

Erick Ogembo Said...


Hi. Your code snippet really helped my problem. Continue doing good work. Thank you.
March 25, 2019 at 2:42 PM

LEAVE A REPLY

keyboard_double_arrow_up
https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 10/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menuComment* search

Your Name*

Your Email*

Your Website

I'm not a robot


reCAPTC
Privacy - Terms

Post Comment

SUBSCRIBE FOR FREE NEWSLETTER


Join our 1M+ subscribers and get the latest tutorials and resources, straight to your inbox.

Enter your email...

SUBSCRIBE

keyboard_double_arrow_up
https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 11/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menu search

TRENDING TUTORIALS

Convert HTML to PDF using JavaScript


Upload and Store Image File in Database using PHP and MySQL
Multi-select Dropdown List with Checkbox using jQuery
Store and Retrieve Image from MySQL Database using PHP
Login with Google Account using PHP
Login with Facebook using PHP
Dynamic Dependent Select Box Dropdown using jQuery, Ajax and PHP
Add Remove Input Fields Dynamically using jQuery

TOPICS all topics

PHP CodeIgniter

WordPress JavaScript

GoogleMap HTML&CSS

Web Development Drupal

Bootstrap CakePHP

Laravel PayPal

keyboard_double_arrow_up
https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 12/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

menu search

LATEST HOW TO GUIDES

How to Save Output of a PHP File in an HTML File


How to change Page Orientation to Landscape in JavaScript window.print()
How to Hide DIV Element After Some Time Interval using jQuery
How to Get the Current Year to Display Dynamic Year in Copyright using JavaScript
How to Validate File Size while Uploading using JavaScript or jQuery

CodexWorld is the most popular Programming & Web Development website aiming to provide the best
online resources for web application developers and designers.

ABOUT US CONTACT

radio_button_checked About CodexWorld radio_button_checked Contact Us


radio_button_checked Write For Us radio_button_checked Advertise keyboard_double_arrow_up
TERMS EXTRA LINKS
https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 13/14
9/7/23, 1:39 AM Upload Multiple Images and Store in Database using PHP and MySQL - CodexWorld

radio_button_checked Terms & Conditions


menu
radio_button_checked Privacy Policy
radio_button_checked Q&A Community
radio_button_checked Online Tools
search

gavel Terms & Condition verified_user Privacy Policy

Copyright © 2023 CodexWorld. All rights reserved.

keyboard_double_arrow_up
https://www.codexworld.com/upload-multiple-images-store-in-database-php-mysql/ 14/14

You might also like