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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read