Open In App

How to Upload Image into Database and Display it using PHP ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Uploading the image/videos into the database and displaying it using PHP is the way of uploading the image into the database and fetching it from the database. Using the PHP code, the user uploads the image or videos they are safely getting entry into the database and the images should be saved into a particular location by fetching these images from the database.
If any of the websites contain the functionality to upload images/videos with some detail, then by using this code we will upload the image into your database and whether you would like to ascertain what the person has got to be uploaded. And by this code the image which is uploaded that where save in your system where you are given the location.

Approach: Make sure you have XAMPP or WAMP server installed on your machine. In this tutorial, we will be using the WAMP server.

1. Create Database: First, we will create a database named ‘geeksforgeeks‘. You can use your existing database or create a new one.

create database “geeksforgeeks”

2. Create Table: Create a table named ‘image‘. The table contains two fields: 

  • id – int(11)
  • filename – varchar(100)

The id should be in Auto incremented(AI). Your table structure should look like this:

table structure of “image”

Or you can create a table by copying and pasting the following code into the SQL panel of your PHPMyAdmin.

CREATE TABLE IF NOT EXISTS `image` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `filename` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

To do this from SQL panel refer to the following screenshot.

create a table ‘image” from the SQL panel

We will be using Bootstrap here to use Bootstrap’s form control. Below is the code to include the Bootstrap CDN link in the head section of the HTML code.

<link rel=”stylesheet” href=”https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css”>

Creating folder and files:

We will now create a folder named “image“. The files uploaded by the client on the server will be stored in this folder. Create index.php and style.css. Keep your main project folder (for example here.. GeeksForGeeks) in the “C://wamp64/www/“, if you are using WAMP or “C://xampp/htdocs/” folder if you are using the XAMPP server respectively. The folder structure should look like this:

folder structure

Program: Now, we will create an HTML form for uploading image files (you can upload any type of file like .pdf or .mp4) and will display the uploaded image.

  • HTML code: 

HTML




<!DOCTYPE html>
<html>
   
<head>
    <title>Image Upload</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
   
<body>
    <div id="content">
        <form method="POST" action="" enctype="multipart/form-data">
            <div class="form-group">
                <input class="form-control" type="file" name="uploadfile" value="" />
            </div>
            <div class="form-group">
                <button class="btn btn-primary" type="submit" name="upload">UPLOAD</button>
            </div>
        </form>
    </div>
    <div id="display-image">
    <?php
        $query = " select * from image ";
        $result = mysqli_query($db, $query);
 
        while ($data = mysqli_fetch_assoc($result)) {
    ?>
        <img src="./image/<?php echo $data['filename']; ?>">
 
    <?php
        }
    ?>
    </div>
</body>
 
</html>


Explanation of PHP code: 

  • We are first selecting the records from the table in the $query variable.
  • Then the $result will execute the query.
  • While loop is used to fetch all the records in the $data to fetch the image from the database.
  • And finally, the fetched images are displayed with the help of the <img> tag. In the <img> tag we are passing the location of the file uploaded on the server and the name of the image file in our database.
  • CSS code: The style.css is the file that styles the form into a new design and the code is given below. 
     

CSS




*{
    margin: 0;
      padding: 0;
      box-sizing: border-box;
}
 
#content{
    width: 50%;
    justify-content: center;
    align-items: center;
    margin: 20px auto;
    border: 1px solid #cbcbcb;
}
form{
    width: 50%;
    margin: 20px auto;
}
 
#display-image{
    width: 100%;
    justify-content: center;
    padding: 5px;
    margin: 15px;
}
img{
    margin: 5px;
    width: 350px;
    height: 250px;
}


You can copy the above code and mention it into the main code directly or create a link as same in the HTML code and attach it with the main code which is given below. As mentioned that if you link the stylesheet file you should create another file in .css format and save it in the place where the main file is to be saved. The form created with the help of the POST method and the enctype=”multipart/form-data” is the action which encodes the files and allows you to send them through POST.
Now we are working on the PHP code for the transfer of the image from any folder of the system in a particular folder which you are mentioning and storing it into the database as a directory.
 

  • PHP code: The PHP code is for the uploading images, the file name is saved with the index.php, you can also save it with another name as you prefer. 
     

PHP




<?php
error_reporting(0);
 
$msg = "";
 
// If upload button is clicked ...
if (isset($_POST['upload'])) {
 
    $filename = $_FILES["uploadfile"]["name"];
    $tempname = $_FILES["uploadfile"]["tmp_name"];
    $folder = "./image/" . $filename;
 
    $db = mysqli_connect("localhost", "root", "", "geeksforgeeks");
 
    // Get all the submitted data from the form
    $sql = "INSERT INTO image (filename) VALUES ('$filename')";
 
    // Execute query
    mysqli_query($db, $sql);
 
    // Now let's move the uploaded image into the folder: image
    if (move_uploaded_file($tempname, $folder)) {
        echo "<h3>  Image uploaded successfully!</h3>";
    } else {
        echo "<h3>  Failed to upload image!</h3>";
    }
}
?>


Explanation: The following are the explanation to create the PHP code which is the following: 

  • The error_reporting(0) is for getting 0 error while PHP code is running.
  • $_files work behind the scene. It is being used to upload files via the HTTP POST method and hold the attributes of files.
  • $filename is a name used to uniquely identify a computer file stored in a file system.
  • $tempname is used to copy the original name of the file which is uploaded to the database as the temp name where the image is stored after upload.
  • $folder defines the path of the uploaded image into the database to the folder where you want to be stored. The “./image/” is the folder name where the image is to be saved after the upload. And the $filename is used for fetching or uploading the file.
  • $db, the basic line for any of the PHP code for connecting to the database.
  • $sql is used for inserting the image into the database of the table name image to the variable filename.
  • mysqli_query is the function to execute a query of $db and $sql.
  • Now, let’s move the uploaded image into the folder named the image. The image named folder is saved into the WAMP or XAMPP server folder which is in C drive into the www folder.

Combination of the above codes: The final code of upload the image into MySQL using PHP is as followed. 
 

  • Program: File name: index.php This file combines the HTML and PHP code. 
     

PHP




<?php
error_reporting(0);
 
$msg = "";
 
// If upload button is clicked ...
if (isset($_POST['upload'])) {
 
    $filename = $_FILES["uploadfile"]["name"];
    $tempname = $_FILES["uploadfile"]["tmp_name"];
    $folder = "./image/" . $filename;
 
    $db = mysqli_connect("localhost", "root", "", "geeksforgeeks");
 
    // Get all the submitted data from the form
    $sql = "INSERT INTO image (filename) VALUES ('$filename')";
 
    // Execute query
    mysqli_query($db, $sql);
 
    // Now let's move the uploaded image into the folder: image
    if (move_uploaded_file($tempname, $folder)) {
        echo "<h3>  Image uploaded successfully!</h3>";
    } else {
        echo "<h3>  Failed to upload image!</h3>";
    }
}
?>
 
<!DOCTYPE html>
<html>
 
<head>
    <title>Image Upload</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
 
<body>
    <div id="content">
        <form method="POST" action="" enctype="multipart/form-data">
            <div class="form-group">
                <input class="form-control" type="file" name="uploadfile" value="" />
            </div>
            <div class="form-group">
                <button class="btn btn-primary" type="submit" name="upload">UPLOAD</button>
            </div>
        </form>
    </div>
    <div id="display-image">
        <?php
        $query = " select * from image ";
        $result = mysqli_query($db, $query);
 
        while ($data = mysqli_fetch_assoc($result)) {
        ?>
            <img src="./image/<?php echo $data['filename']; ?>">
 
        <?php
        }
        ?>
    </div>
</body>
 
</html>


  • Output: Finally, you should be able to upload the images to the database and display it by fetching them from the database.
     

output

Conclusion: The uploaded image into the database with the PHP code is simple and used for various purposes. The code helps to upload the image and then uploaded the image into the database and can be shown in another folder.
One thing you should note is that when you are running this program there should be a possibility that the image is not uploaded more than 2 MB because the PHP program has set the default value of uploading an image of 2 MB and posting the image of 8 MB. For exceeding the size of uploading the image you should follow the following steps:
 

  • First, open the C drive, then open the folder WAMP or XAMPP server.
  • Then open the bin folder.
  • Open the PHP version folder (PHP 5.6.31 folder) (KINDLY NOTE THAT IF YOU HAVE ANOTHER VERSION OF PHP YOU SHOULD OPEN THAT ALSO)
  • Then search php.ini. Open it and then search the two variables and change with them. The variables are: 
     
upload_max_size = 100M
post_max_filesize = 100M
  • Save with this change and then open 
C:\wamp64\bin\apache\apache2.4.27\bin
  • and search for the php.ini file. Change the same thing which is above mention.
  • Restart the WAMP or XAMPP server and then run the code.

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Last Updated : 03 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments