How to Upload Image into Database and Display it using PHP ?
Last Updated :
29 Jul, 2024
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 panelWe 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/[email protected]/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
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<link rel="stylesheet"
href=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<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: index.php This file combines with 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" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<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.
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.
Similar Reads
How to Insert Form Data into Database using PHP ?
In modern web development, Handling User Input is a fundamental task. One of the most common Operations is capturing data from a form and inserting it into database. PHP, combined with MySQL, offers a straightforward and powerful way to achieve it.Here, we will see complete process of inserting form
4 min read
How to fetch data from localserver database and display on HTML table using PHP ?
In this article, we will see how we can display the records in an HTML table by fetching them from the MySQL database using PHP. Approach: Make sure you have XAMPP or WAMP server installed on your machine. In this article, we will be using the WAMP server. WAMP Server is open-source software for th
4 min read
How to Display Data from CSV file using PHP ?
We have given the data in CSV file format and the task is to display the CSV file data into the web browser using PHP. To display the data from CSV file to web browser, we will use fgetcsv() function. Comma Separated Value (CSV) is a text file containing data contents. It is a comma-separated value
2 min read
Upload pdf file to MySQL database for multiple records using PHP
We will upload multiple records to the database and display all the records from the database on the same page. In this article, we will see how we can upload PDF files to a MySQL database using PHP. Approach: Make sure you have XAMPP or WAMP installed on your machine. In this tutorial, we will be
7 min read
How to append data in JSON file through HTML form using PHP ?
The purpose of this article is to append data to a JSON file through HTML form using PHP. Approach 1: If the JSON file is not created then we create a new JSON file, send data to it, and append data in it. To see how to create a JSON file by taking data from the HTML form, refer this link. Approach
4 min read
Signup form using PHP and MySQL Database
The task is to create and design a sign-up form in which if the user enters details, the HTML form data are inserted into our MySQL server database. Approach: First task is that we have to create our MySQL server Database and a Table according to our requirements. We connect our MySQL server Databas
4 min read
How to select and upload multiple files with HTML and PHP, using HTTP POST?
In this article, we will look at how to upload multiple files with HTML and PHP. Multiple image upload allows the user to select multiple files at once and upload all files to the server. index.html Create a simple HTML page to select multiple files and submit it to upload files on the server. Here,
3 min read
How to connect the Database with PHP DOM page ?
In this article, we will see how to connect the database with the PHP DOM page? Approach: Make sure you have XAMPP or WAMP installed on your machine. In this tutorial, we will be using the XAMPP server. To connect the database with the PHP DOM page, follow the steps given below: 1. Create Database:
3 min read
How to create admin login page using PHP?
In this article, we will see how we can create a login page for admin, connected with the database, or whose information to log in to the page is already stored in our database. Follow the steps to create an admin login page using PHP: Approach: Make sure you have XAMPP or WAMP installed on your w
4 min read
How to delete a file using PHP ?
To delete a file by using PHP is very easy. Deleting a file means completely erase a file from a directory so that the file is no longer exist. PHP has an unlink() function that allows to delete a file. The PHP unlink() function takes two parameters $filename and $context. Syntax: unlink( $filename,
2 min read