Image not displaying from database php

image is not displaying from the database it show just showing broken image

Image not displaying from database php

15

$photo is path right

then try this

echo '
Image not displaying from database php

Moving from the comments, this is the fix you need:

echo '
Image not displaying from database php

DirtyBitDirtyBit

16.3k4 gold badges30 silver badges54 bronze badges

Change second last line with this

echo '
';

This will work if $photo path is correct...

answered Sep 25, 2015 at 16:20

Image not displaying from database php

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

Insert Image File in MySQL

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.

Create Database Table

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;

Database Configuration (dbConfig.php)

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.

// Database configuration  
$dbHost     "localhost"
$dbUsername "root"
$dbPassword "root"
$dbName     "codexworld"// Create database connection 
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);  // Check connection 
if ($db->connect_error) { 
    die(
"Connection failed: " $db->connect_error); 
}

Image Upload Form

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.

  • method="post"
  • enctype="multipart/form-data"
<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>

Store Image File in Database (upload.php)

The upload.php file handles the image upload and database insertion process.

  • Check whether the user selects an image file to upload.
  • Retrieve the content of image file by the tmp_name using PHP file_get_contents() function.
  • Insert the binary content of the image in the database using PHP and MySQL.
  • Show the image uploading status to the user.
// 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($fileNamePATHINFO_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;
?>

Retrieve image from database (view.php)

In the view.php file, we will retrieve the image content from the MySQL database and list them on the web page.

  • The data, charset, and base64 parameters in the src attribute, are used to display image BLOB from MySQL database.
// 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");
?> if($result->num_rows 0){ ?>
    <div class="gallery">
        while($row $result->fetch_assoc()){ ?>
            <img src="data:image/jpg;charset=utf8;base64,echo base64_encode($row['image']); ?>" />
        ?>
    div>

}else{ ?>
    <p class="status error">Image(s) not found...p>

?>

Upload Multiple Images and Store in Database using PHP and MySQL

Conclusion

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.

Are you want to get implementation help, or modify or enhance the functionality of this script? Submit Paid Service Request

If you have any questions about this script, submit it to our QA community - Ask Question

How to get image in php from database?

Store Image File in Database (upload..
Check whether the user selects an image file to upload..
Retrieve the content of image file by the tmp_name using PHP file_get_contents() function..
Insert the binary content of the image in the database using PHP and MySQL..
Show the image uploading status to the user..

How to load image in php?

php header be the image type. header('Content-Type: image/jpeg'); Then you can use the GDImage library in PHP to load the image, and output it. Or you can read the file and output it.

How to retrieve blob image from MySQL database using php?

php"; if (isset($_GET['image_id'])) { $sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" ..
get image data and type from MySQL BLOB..
Set the content-type as image (image/jpg, image/gif, …) using PHP header()..
print image content..

How to upload image in MySQL php?

Get the file extension using pathinfo() function in PHP and validate the file format to check whether the user selects an image file. Upload image to server using move_uploaded_file() function in PHP. Insert image file name in the MySQL database using PHP.