Generally, when we upload image file in PHP, the uploaded image is stored in a directory of the server and the respective image name is stored in the database. At the time of display, the file is retrieved from the server and the image is rendered on the web page. But, if you don’t want to consume the space of the server, the file can be stored in the database only. You can upload an image without storing the file physically on the server using the MySQL database. It’s very easy to store and retrieve images from the database using PHP and MySQL.
If you’re concerned about the server space and need free space on your server, you can insert the image file directly in the database without uploading it to the directory of the server. This procedure helps to optimize the server space because the image file content is stored in the database rather than the server. In this tutorial, we will show you how to store image files into the MySQL database and retrieve images from the database using PHP.
Before getting started to integrate file upload with the database, take a look at the file structure.
store_retrieve_image_from_database/ ├── dbConfig.php ├── index.php ├── upload.php ├── view.php └── css/ └── style.css
MySQL has a BLOB (binary large object) data type that can hold a large amount of binary data. The BLOB data type is perfect for storing image data in the database. In MySQL, four BLOB types are available – TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. The LONGBLOB data type is perfect to store the image file data.
To store the file content, a table is required in the database. The following SQL creates an images
table with the LONGBLOB data type field in the MySQL database.
CREATE TABLE `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`image` longblob NOT NULL,
`created` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The dbConfig.php
file is used to connect and select the database. Specify the database host ($dbHost
), username ($dbUsername
), password ($dbPassword
), and name ($dbName
) as per your MySQL database credentials.
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld_db";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
Create an HTML form with a file input field to select an image file for upload. Make sure the <form> tag contains the following attributes.
<form action="upload.php" method="post" enctype="multipart/form-data">
<label>Select Image File:</label>
<input type="file" name="image">
<input type="submit" name="submit" value="Upload">
</form>
The upload.php
file handles the image upload and database insertion process.
<?php
// Include the database configuration file
require_once 'dbConfig.php';
// If file upload form is submitted
$status = $statusMsg = '';
if(isset($_POST["submit"])){
$status = 'error';
if(!empty($_FILES["image"]["name"])) {
// Get file info
$fileName = basename($_FILES["image"]["name"]);
$fileType = pathinfo($fileName, PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif');
if(in_array($fileType, $allowTypes)){
$image = $_FILES['image']['tmp_name'];
$imgContent = addslashes(file_get_contents($image));
// Insert image content into database
$insert = $db->query("INSERT into images (image, created) VALUES ('$imgContent', NOW())");
if($insert){
$status = 'success';
$statusMsg = "File uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select an image file to upload.';
}
}
// Display status message
echo $statusMsg;
?>
In the view.php
file, we will retrieve the image content from the MySQL database and list them on the web page.
<?php
// Include the database configuration file
require_once 'dbConfig.php';
// Get image data from database
$result = $db->query("SELECT image FROM images ORDER BY id DESC");
?>
<!-- Display images with BLOB data from database -->
<?php if($result->num_rows > 0){ ?>
<div class="gallery">
<?php while($row = $result->fetch_assoc()){ ?>
<img src="data:image/jpg;charset=utf8;base64,<?php echo base64_encode($row['image']); ?>" />
<?php } ?>
</div>
<?php }else{ ?>
<p class="status error">Image(s) not found...</p>
<?php } ?>
Upload Multiple Images and Store in Database using PHP and MySQL
This tutorial helps you to integrate file upload functionality without storing files on the server. You can use this example script to upload & store images in the database, and fetch images from the database, and display them on the webpage using PHP and MySQL. To make the image upload process user-friendly, use jQuery to upload files with progress bar using Ajax and PHP.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
in view.php maybe you forgot to remove slashes before base64_encode()?
stripcslashes()
Thank you very much
nice tutorial for beginners
This is Great …!!
Your explanations are much more clearer and understandable…. I am having a challenge with my file upload, no error but image doesn’t get upload into the database
thanks for your generosity… be blessed
Thanks a lot sir. It really helped me for my project for school students in my country,
Thank you! It was very helpful.
I want to add pdf instead of image kindly help very urgent
Thanks you so much:
It was really helpful.
Hi. Really appreciate you guys. I’ve learnt a great deal from you. Thanks
thank you so much,after a day I finally find my answer by this code, thanks again, its really useful.
good – I got help
Thank you so much, this is really helpful.
how to store image and pdf in postgres as bytea datatype
thank you for the code. The image stored as blob file with extension .bin, how can i show that on the output, it’s not coming
hi,
thank u for ur tutorial.its more then usefull for me
once again thank u bro
Thank you for the help it really helped
Thank you so much it has worked out for me but i have failed to resize it using this code:
echo (”$imgData[\’image\’]” 😉 . what should i do to resize it
how to store image in a particular folder …plss help
See this tutorial – https://www.codexworld.com/php-file-upload/
nice
thanks your tutorial and codes were very helpful.
how to see multiple images
not user type
if you are admin
Dear this code is running successfully.
to see the images you have to open page
like http://localhost/images/view.php?id=3
Thank you so much
Hi There,
when I run the view.php on my browser the image I have uploaded pops up in my preview app and gets downloaded.
It won’t show up in my browser. What I could do for it to open in the browser window?
how to add page on folder through core php (like wordpress)
thank you so much sir