• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Tutsplanet

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Twitter Trends
  • Tools
  • About Us

Programming

Upload Multiple Images and Store in Database using PHP and MySQL.

Nov 12, 2019 Editorial Staff 2 Comments

Share
Tweet
Share
16 Shares

File upload is an essential part in any web application, so we are demonstrating a multiple file uploader in PHP and MySQL. In Our example code, we will implement the following functionalities to demonstrate the multiple images upload in PHP. Here we will not be using any framework, but just pure PHP for file upload.

  • An HTML form to select multiple images
  • Uploading images to the server using PHP.
  • Storing the file names in the database and physical file in a folder using PHP and MySQL .

Database Table

In order to save the filenames in the database we need to create the database table first. Run the following statements in the MySql wizard to create the table.

CREATE TABLE `upload_images` (
  `id` int(11) NOT NULL,
  `image` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `upload_images`
  ADD PRIMARY KEY (`id`);

Database Configuration And Connection

We don’t write the database config and connection in the main file directly, but we will use a separate config file to store the credentials and establish the database connection. Finally,  we will call this function inside the form and upload function.

<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "tutorials";

try {
    $conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    
}
catch(PDOException $e)
{
    echo "Connection failed: " . $e->getMessage();
}

File Upload Form

Our input form will have a file field and a form with enctype="multipart/form-data".

<div class="col-lg-7">
	<form action="" method="post" enctype="multipart/form-data">
		<label>Select Image(s):</label>
		<input type="file" name="files[]" multiple >
		<br>
		<input type="submit" name="submit" value="Upload">
	</form>
</div>

Uploading Files Using PHP

First of all we are not using a separate file for HTML form & upload action  in PHP, but will use the same file with a POST check. If the REQUEST_METHOD is post, it means the form is fired. This file handles the multiple image upload functionality.

Key Points

  • First we include the database connection file in the first line.
  • Check whether form is posted
  • Checking the file types to see if it’s allowed types
  • If the validation passed, use move_uploaded_file to upload the file to folder.
  • Finally, saves the file name to database to access it later.
<?php
require_once  "dbconnect.inc.php";

$errors = array();
$success = array();
if(strtolower($_SERVER['REQUEST_METHOD']) == 'post') {

    $uploadDir = 'uploads/';
    $allowTypes = array('jpg','png','jpeg','gif');

    if(!empty(array_filter($_FILES['files']['name']))){
        foreach($_FILES['files']['name'] as $key=>$val){
            $filename = basename($_FILES['files']['name'][$key]);
            $targetFile = $uploadDir.$filename;
            if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], $targetFile)){
                $success[] = "Uploaded $filename";
                $insertQrySplit[] = "('$filename')";
            }
            else {
                $errors[] = "Something went wrong- File - $filename";
            }
        }

        //Inserting to database
        if(!empty($insertQrySplit)) {
            $query = implode(",",$insertQrySplit);
            $sql = "INSERT INTO upload_images (image) VALUES $query";
            $stmt= $conn->prepare($sql);
            $stmt->execute();
        }
    }
    else {
        $errors[] = "No File Selected";
    }

}
?>

Conclusion

In this example, we have shown easiest way to upload multiple images using PHP and MySql. You may use this code as a starting point of your application.

You can find full code here


Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

View all posts by Editorial Staff

Reader Interactions

Comments

  1. Butul says

    Jan 20, 2021 at 12:44 pm

    I had done upload multiple image store in php using your code but i want to know how can we reterieve and show that data in html img tag un php ?? Can u help me out in that ??

    Reply
    • Editorial Staff says

      Jan 23, 2021 at 4:56 pm

      It’s very simple to do that, you can write a simple SELECT query from the database and show the images in HTML tags

      $sql = "SELECT * FROM upload_images";
      ///And in the loop you can list all the images

      Reply

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Quick Links

  • Top 21 Website Ideas To Make Money Online in 2021
  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Replace “\n” with new line characters, using Notepad++
  • Using Third-Party Libraries in Codeigniter
  • Upload Multiple Images and Store in Database using PHP and MySQL.
  • Hierarchical Tree view Category Example in Laravel
  • Laravel Image Intervention Tutorial With Example
  • How to import sql file in MySQL database using PHP?
  • Free VAT Calculator Online

Subscribe

* indicates required



Search Here

Share

   



Hot topics

  • Replace “\n” with new line characters, using Notepad++ 16 views
  • Solution: windows photo viewer opens each time save a pic file 11 views
  • A Simple YouTube Video Downloader Script in PHP 10 views
  • How to Create PDF File From HTML Form Using Fpdf? 9 views
  • How to create and download a Zip file with PHP 8 views
  • Open a URL in a new tab using JavaScript 8 views
  • Simple PHP Shopping Cart 7 views
  • How to enter new line in Microsoft Teams? 7 views
  • Hierarchical Tree view Category Example in Laravel 7 views
  • Laravel Eloquent Select Column as Alias 7 views

Categories

  • Design & Development
  • Drupal
  • Facebook
  • General
  • How To
  • ios
  • Javascript
  • Linux
  • Magento
  • Marketing
  • News
  • PHP
  • Plugins
  • Programming
  • Snippets List
  • Social Media
  • Softwares
  • Themes
  • Tips
  • Wordpress
  • YouTube























Copyright © 2023 · Planet on Genesis Framework · Powered By BunnyCDN . Network wallpapernoon.com