Professional Documents
Culture Documents
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
// 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;
?>
// Get image data from database
$result = $db->query("SELECT image FROM images ORDER BY id DESC");
?>
<?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 } ?>