In this article, we will see how to upload images using database and display gallery . For image upload we will require an HTML form that allows image uploading , table to store images and PHP script that will display all uploaded images of database with delete option.

For this we need to create a table in our database , img_upload

create table img_upload (img_id int AUTO_INCREMENT , img_name varchar(255) , img_path varchar(255) , PRIMARY KEY (img_id));

After creating img_upload table, we will create a HTML form that can handle upload and be sure that you don’t forget to include enctype=”multipart/form-data” attribute in FORM field else it won’t work. Multiple attribute will allow to select multiple images together and accept=”image/*” will allow to select only images for uploading.

HTML CODEThis will allow you upload images .

    <form action="img_upload.php" enctype="multipart/form-data" method="POST">
      
        <input type="hidden" name="MAX_FILE_SIZE" value="512000"/>
        <p><strong>File to Upload:</strong> <input type="file" name="fileupload" multiple  accept="image/*"/></p>
        <p><input type="submit" name="submit" value="upload!"></p> </form>

Lets see the important parts of the above HTML code for Image Uploading in PHP:

  • enctype=”multipart/form-data”  : This attribute is mandatory for uploading in PHP, else this functionally will not work properly.
  • input type=”hidden” name=”MAX_FILE_SIZE” value=”51200″ : This will set the maximum size in bytes  of the files that you are willing to accept. As here we have set maximum length of 50 KB. You can allow more large uploads by changing settings in php.ini, upload_max_filesize attribute. After this you are ready to add the upload filed itself.
  • input type=”file” is an INPUT element with the type argument file.
  • multiple attribute allows to select multiple images together.
  • accept=”image/*” this will allow you to only show you images to choose and no other files.

PHP FILE Uploading

With Each upload, entry will occur in database regarding that image upload :

  <?php
      $img_location="";
      if(isset($_POST["submit"]))
      {
             $file_directory = "C:/wamp/www/Freefeast/";
             foreach($_FILES as $file_name => $file_arr)
             {
                 if (is_uploaded_file($file_arr["tmp_name"]))
                 {
                   move_uploaded_file($file_arr["tmp_name"], "$file_directory/".$file_arr["name"]) or die ("Couldn't copy");
                   $img_name =$file_arr["name"]; 
                   $img_location="/Freefeast/" . $file_arr["name"]; 
  
                    mysql_query("INSERT INTO img_upload(img_name, img_path) VALUES ('$img_name','$img_location')");
                    header("Refresh:0");
                 }
              }
         }
 
?>

Code to Display Gallery : With each upload you can see uploaded and all images in gallery. Here we want only four images to be displayed in a single row. With each image, delete option is there and by clicking on that image will be deleted from gallery and database as well.

<table border="1"><tr><th colspan="4"> Image Gallary </th></tr> 
<?php
        $con=mysql_connect("localhost","root",""); // Database Connection
        $db=mysql_select_db("employee",$con); // Selecting Database
        $res = mysql_query("SELECT img_id,img_path FROM img_upload");

        $count=0; 
        while($r=mysql_fetch_row($res))
       {
            if($count == 4 )   // As we want only four images in a single row
            {
                echo "</tr>";
                $count=0;
            }

           if($count == 0)
           {
                echo "<tr>"; 
           }
           echo "<td align='center'><img src='".$r[1]."' height='300' width='300'></br><a href='img_delete.php?imgId=$r[0]>'> <img src='/Delete_Imag_Button.png' height='50' width='100'></a>";
           $count++;
           echo"</td>";
 } 
           if($count > 0)
               echo "</tr>";
 ?>
</table>

Output :

Photo_gallery in PHP

In this code I have used :

  • mysql_connect() : Used to open connection in MySQL and takes three parameter i.e. SERVER,USER_NAME and PASSWORD. we take default values for these parameters i.e. localhost, root and empty string respectively. This function returns a MySQL link identifier on successful connection and return false if fails to open connection.
  • mysql_error() : this returns the text of the error message  from previous MySQL operation and empty string if no error occurred.
  • mysql_select_db() : Sets the current active database on the server which is associated with specified link identifier returned by mysql_connect().
  • mysql_query() : This sends a query to current active database on the server. It takes SQL query as parameter.
  • mysql_fetch_row() : This function get a result row as an enumerated array. It returns numerical array corresponds to the fetched row and moves the internal data pointer ahead.   mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array and each result column is stored in array offset which starts at offset 0.
  • header() : With this  function you can redirect to the another page without any click or link.                                                                              Ex : Header(‘Location : https://www.freefeast.info’);           But the header() function, you have to call before any of the actual output is sent may be HTML tags, blank lines.
  • header(“Refresh:0”) this will refresh the current page and helps to view latest existing data.

Code to Delete Image : img_delete.php

When you click on Delete button it will go to the img_delete.php

 <span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;"><span style="font-size: 13px; line-height: 19px;"> </span></span>&lt;?php
      $con=mysql_connect("localhost","root","");
      mysql_select_db("employee",$con);
      $dnum=$_REQUEST["imgId"];   // Image_id passed form img_upload.php
      $qry="delete from img_upload where img_id='$dnum'";   // delete the image you clicked
      $res=mysql_query($qry);

     if(!$res)
     {   echo "Deletion Error ".mysql_error();  }
      else
     {
           header("location:img_upload.php");
      }
 ?&gt;

Lets see the complete code :

<html>
  <head>
    <title>A simple file upload form</title>
  </head>
 <body>
   <form action="img_upload.php" enctype="multipart/form-data" method="POST">
    <center>
     <input type="hidden" name="MAX_FILE_SIZE" value="512000"/>
     <p><strong>File to Upload:</strong> <input type="file" name="fileupload" multiple accept="image/*"/></p>
     <p><input type="submit" name="submit" value="upload!"></p>
   
    <table border="1"><tr><th colspan="4"> Image Gallary </th></tr> 
    <?php
          $con=mysql_connect("localhost","root",""); // Database Connection
          $db=mysql_select_db("employee",$con); // Selecting Database
          $res = mysql_query("SELECT img_id,img_path FROM img_upload");
        
        $count=0; 
        while($r=mysql_fetch_row($res))
        {
             if($count == 4 )
             {
                 echo "</tr>";
                 $count=0;
             }
             if($count == 0)
             {
                echo "<tr>"; 
             }

           echo "<td align='center'><img src='".$r[1]."' height='300' width='300'></br><a href='img_delete.php?imgId=$r[0]>'> <img src='/Delete_Imag_Button.png' height='50' width='100'></a>";

          $count++; 
          echo"</td>";
       }
       if($count > 0)
            echo "</tr>";
 ?>
   </table>
  </center>
 </form>
</body>
</html>

 
<?php
  $img_location="";
 if(isset($_POST["submit"]))
 {
     $file_directory = "C:/wamp/www/Freefeast/";
     foreach($_FILES as $file_name => $file_arr)
    {
         if (is_uploaded_file($file_arr["tmp_name"]))
         {
            move_uploaded_file($file_arr["tmp_name"], "$file_directory/".$file_arr["name"]) or die ("Couldn't copy");
            $img_name =$file_arr["name"]; 
            $img_location="/Freefeast/" . $file_arr["name"]; 
 
            mysql_query("INSERT INTO img_upload(img_name, img_path) VALUES ('$img_name','$img_location')");
            header("Refresh:0");
 
           // echo "Photo uploaded sucessfully!<br/>";
      }
    }
 }
 ?>