How to Upload Image in PHP and Store in Database and Folder -Easy Ste

Here in this tutorial, I will show you How to Upload Image in PHP and Store in MySQL Database and Server Folder?. There are soo many ways to store an image in a server but here in this tutorial, we use PHP to control the file systems and MySQL databases. We store images in the server directory and use the MySQL database to trace those images. At last, we use data from our database to display those images.

An image can also be stored in a database but this will increase server load as well as database size. So as possible, it is not a good idea to store images in a database. Where server is designed to server file so it will serve image faster than a database.

Complete Tutorial of How to Upload Image in PHP

To make it easier for you to flow the code, I have divided this coding into four parts.

  • Creating a database table
  • HTML form to upload an image.
  • Upload image to server using PHP and Store file name in the MySQL database.
  • Retrieve images from the database and display on the web page.

Create Database Table

To store the image file name we need to create a table in the database. Execute the following SQL and it will create an images table with some basic fields in the MySQL database.

 file_name varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 uploaded_on datetime NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Files and folder we need here

  • uploads (folder)
  • config.php
  • index.php
  • upload.php


By using config.php file we connect our web page to our database so that we can store our image details into the database table. And later on, retrieve that image to display it on our webpage.

For a database connection, we need localhost name $dbHost, database user name $dbUsername, database password $dbPassword, and database name $dbName.

// 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);


In this file, we write a code to make form. From which our user can upload their image. And also display uploaded images into our web page.

<!DOCTYPE html>
  <title>Upload Image</title>
  <form action="upload.php" method="post" enctype="multipart/form-data">
        Select Image File to Upload:
      <input type="file" name="file">
      <input type="submit" name="submit" value="Upload">

  // Include the database configuration file
  include 'config.php';

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

  if($query->num_rows > 0){
      while($row = $query->fetch_assoc()){
          $imageURL = 'uploads/'.$row["file_name"];
      <img src="<?= $imageURL; ?>" />
  <?php }} ?>
upload image layout

The form coding from line 7 – 11 is used to send an image into upload.phpfile with a post method and we use enctype="multipart/form-data"because we are sending an image.

The coding line from 14 – 26 is used to display an image in a webpage just below the form.


This file is used to get an image receives an image detail which is sent from index.php file. Then store the image in uploads folder at last store image details in MySQL database table.

// Include the database configuration file
include 'config.php';
$statusMsg = '';
$backlink = ' <a href="./">Go back</a>';

// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
    // Allow certain file formats
    $allowTypes = array('jpg','png','jpeg','gif','pdf');
    if (!file_exists($targetFilePath)) {
        if(in_array($fileType, $allowTypes)){
                // Upload file to server
            if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
                // Insert image file name into database
                $insert = $db->query("INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
                    $statusMsg = "The file <b>".$fileName. "</b> has been uploaded successfully." . $backlink;
                    $statusMsg = "File upload failed, please try again." . $backlink;
                $statusMsg = "Sorry, there was an error uploading your file." . $backlink;
            $statusMsg = "Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload." . $backlink;
            $statusMsg = "The file <b>".$fileName. "</b> is already exist." . $backlink;
    $statusMsg = 'Please select a file to upload.' . $backlink;

// Display status message
echo $statusMsg;
  • $statusMsgis used to store status message either it is success or failure on upload. Then at the end, we display that message.
  • $backlinkis used to go to the home page.
  • Line 13 if the statement means that the upload process will continue only if the user selects the image and then click the submit button.
  • In 15. We store the extension in an array which we allow our user to upload on the server.
  • 16. The upload process will continue only if the selected image did not already exist in an uploads folder.
  • 17. After that we check does a selected file of a user, contain any of this extension (JPG, JPEG, PNG, GIF, & PDF). If yes, we continue the upload process else we print an error message.
  • 19. If an image is successfully uploaded in uploads folder on the server then we store the image details by using code line 21 and 22.
  • This is how we upload image file into the server using PHP and MySQL Database.

You may also like this handpick tutorial for you.

Also, watch the video of this tutorial.

5 2 votes
Article Rating
Notify of
Newest Most Voted
Inline Feedbacks
View all comments
3 years ago

i love programming but i am having difficulty in learning it

3 years ago

i have been trying to download mysql but it refused to installed. i dont knw what to do now! pls i need help

2 years ago

would you mind sharing the code to upload some content with the image to the database such as the submitter name and commentary about the image – Thanks

Last edited 1 year ago by Nawaraj Shah
#programming,cryptocurrency and Technology world
#programming,cryptocurrency and Technology world
2 years ago

I have been trying to upload an image using PHP and saving the image to the database but I have been having difficulty it is working but the image is not saving on the database please reply to this comment

Last edited 1 year ago by Nawaraj Shah