3 Best Ways on How To Upload Image In PHP
Please spread the love
3 Best Ways on How To Upload Image In PHP And Store In Database folder in 2021

In this tutorial with the help of a diagrams and codes you’ll learn the 3 best ways on how to upload images in PHP and Store in a Database In 2021.

Using PHP and MySQLi to upload images or files is an integral aspect of any web application.

In this article, we’ll go through how to upload images in PHP and store them in a database folder step by step.

This technique can be used with photos, MS Word files, Excel files, or any other file format.

Step 1: Creating an HTML Form for Uploading Images

The first step is to create a file with “index php” and then write a simple HTML form code with only two elements an input file and button element.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html>
<head>
    <title>File Upload to Database</title>
</head>
<body>
            
<div>
<h1>File Upload with PHP and MySQLI</h1>
<form action="" method="post" enctype="multipart/form-data">
                            
                            Upload Images/File : <input type="file" name="uploadfile">
                           </br>
                           
                            <button type="submit" name="submitform">Upload</button>
                        </form>
            </div>
            
</body>
</html>

Now it’s time to explain the above code line by line first write the code of the basic HTML file structure.

Within body write code for HTML Form by opening and closing the form tags and for file elements and then button.

The important step to note here is giving file and button element a proper name and give the attribute name value in the form tag enctype=”multipart/form-data ” attribute is important for uploading a file.

Step 2: Create a Database and Table in PhpMyAdmin

We have created a database with the name of “test” and table with the name of “images”.

The table will contain only two fields. One will be a primary and auto increment “Id” and second will be with the name of “file” which will store the upload file name.

Check the below images to understand the structure of the table and fields.

mysqli-database-table-for-uploadin-image-in-php

 

Step 3: Creating a MySQLI Database Connection in PHP

Write the below code to connect database in PHP. We are using the MySQLI extended version of mysql.

Create a new file with “connection.php” name write the copy and past the code.

?
1
&lt;?php $con=mysqli_connect("localhost","root", "","test"); ?&gt;

Check Also:  Learn WordPress Theme Development Tutorials

Now next step is to include the “connection.php” file in your “index.php” file. We can do this by two PHP functions through “require” and “include”.

I will use the “require” as they do the same work but its more secure and handy to use. Copy and paste the following code in the first line of “index.php” file.

require file in php

 

Step 4: Upload and store images in database with PHP and MySQLI

Create a folder in the with the name upload where all the uploaded images/files will be the store.

In the database we will just store a name of the file and if a file with the same name already exist we will rename the name by adding the current time.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
if(isset($_POST['submitform']))
{
    $dir="upload/";
    $image=$_FILES['uploadfile']['name'];
    $temp_name=$_FILES['uploadfile']['tmp_name'];
    if($image!="")
    {
        if(file_exists($dir.$image))
        {
            $image= time().'_'.$image;
        }
        $fdir= $dir.$image;
        move_uploaded_file($temp_name, $fdir);
    }
        $query="insert IGNORE into `images` (`id`,`file`) values ('','$image')";
        mysqli_query($con,$query) or die(mysqli_error($con));
        
        echo "File Uploaded Suucessfully ";
}

Now its time to write the PHP code for uploading the image and store in a database.

First, we will write an if condition and check weather the file is uploaded and the button is clicked then execute the code.

$_File is a global PHP variable and contain all the information of uploaded file.

$dir is a variable where the path of “upload” folder is  the store. “$temp_name” is used to store the temporary file name of the uploaded image.

“move_upload_file” is a PHP function which takes two arguments first one to pass the variable of temporary location and a second one is the permanent destination. Move_uploaded_file is used to upload a file to a server.

Now write the MySQLI insert query to store the images to the database table. We will store just the uploaded images name and id will be auto increment.

How to Retrieve or show images from Database table

In this section, we will learn how to retrieve or show images from the database table. We will use the “SQL SELECT” query to fetch record from the table.

Learn PHP programming

To show only one record, we simply write the query and execute it while if we want to show all the record form the table, we will use the “while loop” in which the condition will be true until the record is not finished and will retrieve all images.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<div>
<h2>Show All Upload Images</h2>
<table border="1" cellpadding="2" cellspacing="0">
                            
<tr>
                                    
<th>Sr.NO</th>
<th>Name</th>
                            </tr>
                    <?php $i=1; $sql="select * from `images`"; $qry=mysqli_query($con,$sql) or die(mysqli_error($con)); while($row=mysqli_fetch_array($qry)) { ?>
                            
<tr>
                                    
<td><?php echo $i;?></td>
<td><img src="upload/<?php echo $row['file'];?>" width="100" height="100"></td>
                            </tr>
                 <?php $i++; } ?>
                    </table>
            </div>

Use the above code to fetch or retrieve or show images from the database table.

Conclusion

l believe that with the help of this article and with the help of  the diagrams provided above you have been able to understand and also know how to upload image in php and store it in database in 2021

If you have any question in the code or don’t understand any thing in the post do comment I will be happy to help you.

Thanks for reading this article, please don’t forget to share it with friends on all your social media handles, you can also find us on Facebook.

See you Soon!

By Codedportal

Codedportal is the Best Blogging, Digital Marketing, Health and Technology Website.

Leave a Reply

Your email address will not be published. Required fields are marked *