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

Uploading the image/videos into the database and display it using PHP is the way of uploading the image into the database and fetched 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.

First, create the database on XAMPP/WAMP server using phpMyAdmin and give the database name is photos and the table name is image. The table contains two fields:



  • Id – int(11)
  • Filename – VARCHAR(100)

Id should be in Auto incremented(AI). The image of created database is shown below:

Program: Now, we will create a form for uploading images/videos files.

  • HTML code:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!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">
                <input type="file" 
                       name="uploadfile" 
                       value="" />
      
                <div>
                    <button type="submit"
                            name="upload">
                      UPLOAD
                    </button>
                </div>
            </form>
        </div>
    </body>
      
    </html>

    chevron_right

    
    

  • CSS code: The style.css is the file that styles the form into a new design and the code is given below.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    #content{
        width: 50%;
        margin: 20px auto;
        border: 1px solid #cbcbcb;
    }
    form{
        width: 50%;
        margin: 20px auto;
    }
    form div{
        margin-top: 5px;
    }
    #img_div{
        width: 80%;
        padding: 5px;
        margin: 15px auto;
        border: 1px solid #cbcbcb;
    }
    #img_div:after{
        content: "";
        display: block;
        clear: both;
    }
    img{
        float: left;
        margin: 5px;
        width: 300px;
        height: 140px;
    }

    chevron_right

    
    

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 attached 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 saved it on the place where the main file to be saved. The form created with the help of POST method and the enctype=”multipart/form-data is the action which encoding the files and allow you to sent through POST.

Now we are work on the PHP code for the transfer of the image from any folder of the system in a particular folder which you are mention and store 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 with another name as you prefer.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    error_reporting(0);
    ?>
    <?php
      $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", "", "photos");
      
            // 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))  {
                $msg = "Image uploaded successfully";
            }else{
                $msg = "Failed to upload image";
          }
      }
      $result = mysqli_query($db, "SELECT * FROM image");
    ?>

    chevron_right

    
    

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 is 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/” the folder name where the image is to be saved after the upload. And the .$filename is used for fetching or upload the file.
  • $db, the basic line for any of the PHP code for connecting to the database.
  • $sql used for the inserting the image into the database of table name image to the variable filename.
  • mysqli_query is the function to executing query of $db and $sql.
  • Now, let’s move the uploaded image into the folder which named as the image. The image named folder is saved into the WAMP or XAMPP server folder which is in C drive into the www folder.
  • $result function is used for the retrieve the image from the database.

Combination of the above codes: And 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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
    error_reporting(0);
    ?>
    <?php
      $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", "", "photos");
      
            // 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))  {
                $msg = "Image uploaded successfully";
            }else{
                $msg = "Failed to upload image";
          }
      }
      $result = mysqli_query($db, "SELECT * FROM image");
    ?>
      
    <!DOCTYPE html>
    <html>
    <head>
    <title>Image Upload</title>
    <link rel="stylesheet" type= "text/css" href ="style.css"/>
    <div id="content">
      
      <form method="POST" action="" enctype="multipart/form-data">
          <input type="file" name="uploadfile" value=""/>
            
          <div>
              <button type="submit" name="upload">UPLOAD</button>
            </div>
      </form>
    </div>
    </body>
    </html>

    chevron_right

    
    

  • Output: Finally, you should upload the images, videos of less than 100 MB. If you want to exceed more than change with the same.

Conclusion: The uploaded image into the database with the PHP code is having simple and using 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 that when you are run this program there should be a possibility that the image is not uploaded more than the 2 MB because the PHP program has set the default value of uploading an image of 2 MB and post 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 varible and change with it. 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 the php.ini. Change the same thing which are above mention.

  • Restart the WAMP or XAMPP server and then run the code.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.