Spread the word.

Share the link on social media.

Share
  • Facebook
Have an account? Sign In Now

Sign Up


Have an account? Sign In Now

Sign In


Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask question.


Forgot Password?

Need An Account, Sign Up Here
Sign InSign Up

Ha Giang Local Expert®

Ha Giang Local Expert® Logo Ha Giang Local Expert® Logo

Ha Giang Local Expert® Navigation

  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • Home
  • About Us
  • Blog
  • Contact Us

Share & grow the world's knowledge!

We want to connect the people who have knowledge to the people who need it, to bring together people with different perspectives so they can understand each other better, and to empower everyone to share their knowledge.

Ask A Question
Home/ Questions/Q 266
Next
canomi
  • 0
canomi
Asked: March 6, 20202020-03-06T08:49:42+07:00 2020-03-06T08:49:42+07:00In: Web Development

Upload Multiple Images and Store in Database using PHP and MySQL

  • 0

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;

Database Configuration (dbConfig.php)

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 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="" 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.
  • 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 = ''; 
    $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], $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: '.trim($errorUpload, ' | '):''; 
                $errorUploadType = !empty($errorUploadType)?'File Type Error: '.trim($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; 
} 
?>

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="" />
<?php }
}else{ ?>
    <p>No image(s) found...</p>
<?php } ?> 
mysqlphpupload multiple images
  • 0 0 Answers
  • 176 Views
  • 0 Followers
  • 0
Answer
Share
  • Facebook

    Leave an answer
    Cancel reply

    You must login to add an answer.


    Forgot Password?

    Need An Account, Sign Up Here

    Sidebar

    Stats

    • Questions 43
    • Answers 37
    • Posts 37
    • Comments 4
    • Best Answers 18
    • Users 253
    • Popular
    • Answers
    • Tags
    • canomi

      Ha Giang Loop - On Own By Rental Car?

      • 3 Answers
    • wordpress

      Ha Giang 3 days loop itinerary + Ban Gioc waterfalls

      • 2 Answers
    • Aaron Aiken

      Hire a car with driver in Ha Giang

      • 2 Answers
    • Anonymous

      is the ha giang loop dangerous? or safe?

      • 2 Answers
    • Aaron Aiken

      Where is the Phuong Thien Cave in Ha Giang?

      • 2 Answers
    • canomi
      canomi added an answer If you need a tourguide for you trip so you… January 9, 2021 at 8:54 pm
    • canomi
      canomi added an answer It’s true that you can visit Ha Giang at any… January 9, 2021 at 8:47 pm
    • mvbergen
      [Deleted User] added an answer I heard that from May to Oct is the best… January 9, 2021 at 8:40 pm
    • mvbergen
      [Deleted User] added an answer Hi Alex, I am also going to Ha Giang in… January 9, 2021 at 8:40 pm
    • Tony
      Tony added an answer The weather in March is good, little bit cold and… January 9, 2021 at 6:49 pm
    3 days loop analytics bootstrap modal cao bang car and driver car for rent in ha giang car rental in ha giang cave covid-19 treatment covid-19 vietnam disable a button drone vietnam english english speaking driver float value google ha giang ha giang homestay ha giang hostel ha giang hotel ha giang loop ha giang loop accidents ha giang loop advice ha giang loop tour ha giang market ha giang motorbike tour ha giang tour ha giang travel hire car html email ios mail javascript jquery jquery.click() local market multiple selected mysql noong lake northern vietnam onclick php rent motorbike upload multiple images wordpress yandex mail

    Top Members

    canomi

    canomi

    • 11 Questions
    • 161 Points
    Aaron Aiken

    Aaron Aiken

    • 0 Questions
    • 24 Points
    galaxy35

    galaxy35

    • 0 Questions
    • 20 Points
    • Meet The Team
    • Blog
    • About Us
    • Contact Us

    © 2020 Discy. All Rights Reserved
    With Love by VZN.VN.

    Explore

    • Home
    • Communities
    • Questions
      • New Questions
      • Trending Questions
      • Must read Questions
      • Hot Questions
    • Polls
    • Tags
    • Badges
    • Users
    • Help

    Insert/edit link

    Enter the destination URL

    Or link to existing content

      No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.