All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

PHP Code For Image Upload And Display

Last Updated : Jul 1, 2023

PHP Code For Image Upload And Display

In this tutorial we will show you the solution of PHP code for image upload and display, we can upload any images on database then we can display those images by retrieve from database and for uploading images has no limit.

In database we can do store, edit, update or delete these operations and mainly database used for collects and store all user information.

When we need some information from database we can retrieve using php because it is a server side language.

Step By Step Guide On PHP Code For Image Upload And Display :-

Here we need to collect server details and make request to server by ‘mysqli_connect()’.

For collect user inputs we need to create html elements of input tags with three types one is ‘text’ for getting image title and ‘file’ type for upload files, another one is for ‘submit’.

When submit button clicks by user it loads uploading program, in that we generating random number before file name for avoid replacing images with same name on database.

Then we need to execute insertion query with ‘uploading file, file title’ details and those details successfully inserted with database.

Another input tag for ‘display’ all images from our table ‘fileup’, it’s done when user clicks on ‘Display’ button.

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload And Display</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<label>Title</label>
    <input type="text" name="title">
    <label>File Upload</label>
    <input type="File" name="file">
    <input type="submit" name="submit">
    <input type="submit" name="display" value="Display">
</form>
<table>
    <tr>
        <th>name</th>
        <th>image</th>
</tr>
<?php
$localhost = "localhost"; #localhost
$dbusername = "root"; #username of phpmyadmin
$dbpassword = ""; #password of phpmyadmin
$dbname = "dbase"; #database name
#connection string
$conn = mysqli_connect($localhost,$dbusername,$dbpassword,$dbname);
if (isset($_POST["submit"]))
 {
    #retrieve file title
        $title = $_POST["title"];
    #file name with a random number so that similar dont get replaced
     $pname = rand(1000,10000)."-".$_FILES["file"]["name"];
    #temporary file name to store file
    $tname = $_FILES["file"]["tmp_name"];
     #upload directory path
    $uploads_dir = 'img';
    #TO move the uploaded file to specific location
    move_uploaded_file($tname, $uploads_dir.'/'.$pname);
    #sql query to insert into database
    $sql = "INSERT into fileup(title,image) VALUES('$title','$pname')";
    if(mysqli_query($conn,$sql)){
    echo "File Sucessfully uploaded";
    }
    else{
        echo "Error";
    }
}if( (isset($_POST["display"]))){
    $sql = "SELECT * FROM fileup";
    $q=mysqli_query($conn,$sql);
    while($row=mysqli_fetch_array($q)){
        ?>
        <tr>
        <td><?php echo $row['title'];?></td>
        <td><img src="img/<?php echo $row["image"];?>" height="100" width="100"></td>
       </tr>
   <?php }}
    ?>
    </table>
    </body>
</html>
  1. A php script can be placed anywhere in the document. A php script starts with <?php and end with ?> tags.
  2. The default file extension for php files is “.php” and php each statements end with ‘;’ semicolon. Between start and end tag we need to define our program in php.
  3. First we need to create database with name ‘dbase’ and table name ‘fileup’ with three columns namely ‘id,title,image’. That ‘id’ column type must be ‘primary and auto_increment’ and title type is ‘varchar’, image type is ‘varbinary’.
  4. We need to collect server details so we used variables ‘$localhost,$dbusername,$dbpassword,$dbname’ for collecting our server details.
  5. In variable ‘$localhost’ we stored server name and its server name will available on server page top left end. Most of time it’s name will ‘localhost’.
  6. Variable ‘$dbusername’ used for store ‘user name’ its most of time default value also ‘root’, ‘$dbpassword’ variable for store ‘user password’ and ‘$dbname’ variable for store ‘database name’.
  7. Database name will definitely vary because we can give any name for our database when we are creating. If you use above code then create database on xampp server with name ‘dbase’.
  8. Then using ‘mysqli_connect()’ method with parameter of server details we request server for granting permission.
  9. When request grant means its finding database name on xampp server and when it finds its connection will success. If the database name not exit or any server details not correct then it throws error on browser webpage.
  10. So we have give correct details of server and database then we can achieve result easily. First if() condition for checking whether the submit button clicked or not.
  11. We are storing user inputs, title of image to variable ‘$title’. Then we generating random number for appends to file name front because it avoids replacing and we need to give directory name to variable ‘$uploads_dir’. This directory must present in same location of this file location and those file and directory must be in server location.
  12. We created earlier temporary location, it’s for move our files to that location and we exexcuting insert query for insertion of user inputs ‘title, file’ to our table ‘fileup’ in database ‘dbase’ on server.
  13. Next if() condition for checks our insertion whether executed successfully or not. When it success it throws ‘file successfully uploaded’ message on webpage otherwise error message will thrown on webpage.
  14. After uploading image on database when user clicks on ‘Display’ button, it loads retrieving program. First we need to create select query for selecting all datas from table and stored to variable ‘$sql’.
  15. For executing the select query we need to use ‘mysqli_query()’ function with connection string ‘$conn’ then result stored to variable ‘$q’. Then using while loop for fetch all stored ‘image title and image’ on table ‘fileup’ by ‘mysqli_fetch_array()’ function.
  16. In loop fetching datas row by row from database table those are stored to variable ‘$row’ then each row column values of ($row['title'] is refers ‘image title’, $row["image"] is refers ‘image’) printed on webpage line by line. Within a while loop we printed those fetched datas on html table.
  17. Then result will printed on our webpage using ‘echo()’ with ‘connection succeed’ string. It also a statement for print any values in php.

Conclusion :-

In conclusion we are able to know how to upload and display any images on mysql database using php.

When work with php we need to create and process php files at server location and then we need to start the server before execute the program.

When user gives inputs and clicks submit button it will successfully uploaded on our database table in server with success message display on webpage for user verification, otherwise it throws error message on webpage browser.

Same as for display when user clicks on ‘Display’ button fetched all data from database table then printed on webpage with html table format.

I hope this tutorial on PHP code for image upload and display helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Riya

A recent graduate with a Bachelor of Technology (B.Tech) in Computer Science from India. She is passionate about leveraging technology to solve real-world problems. With a strong foundation and experience in programming languages such as Python, Django, HTML, CSS, and JavaScript, java, php and have honed her skills through hands-on projects and coursework.

Follow Riya On Linkedin 🡪