Report this

What is the reason for this report?

How to display BLOB type of image in webpage in php

Posted on February 24, 2021

I want to ask about how to display blob type image in the php webpage. I tried too many ways , but It’s still seem like no way out.

–Here is the code that I storage the image type:

$URL = $_POST['link'];
        $title = $_POST['title'];
        $content = $_POST['textEditor'];
        // image format
        $avatar = $_POST['image'];
        $author = $_SESSION['username'];
        $active = $_POST['active'];
        $dateTime = $_POST['datetime'];
        $category = $_POST['types'];
        $query = "INSERT INTO news_post(news_link, news_title, news_content, news_image, author, status, create_date, category) VALUES("
                . ":link, :title, :textEditor, :image, :author, :active, :datetime, :types);";
        $statement = $conn->prepare($query);
        $statement->bindValue(':link', $URL);
        $statement->bindValue(':title', $title);
        $statement->bindValue(':textEditor', $content);
        $statement->bindValue(':image', $avatar);
        $statement->bindValue(':author', $author);
        $statement->bindValue(':active', $active);
        $statement->bindValue(':datetime', $dateTime);
        $statement->bindValue(':types', $category);
        $statement->execute();
        $statement->closeCursor();

It works good and storage the image file into the database, and the image field that show up the bytes of the images.

Then, I want to display all the news table on webpage

— here is my code that I selected all the data from db:

$query = "SELECT news_post.newsID, news_post.news_link, news_post.news_title, news_post.news_content, news_post.news_image, news_post.author, status_pots.status , news_post.create_date, category.category FROM ((news_post INNER JOIN status_pots ON news_post.`status`=status_pots.statusID) INNER JOIN category ON news_post.category=category.typeID )";
$statement = $conn->prepare($query);
$statement->execute();
$news = $statement->fetchAll();
$statement->closeCursor();

Everything display as perfect except the image field, It could not retrieve data from BLOB and display it on the table on the page.

And the code below is my table data that show on page:

<?php foreach ($news as $newsPost) : ?>

                    <tr>
                        <td>
                            <?php echo $newsPost['newsID']; ?>
                        </td>
                        <td>
                            <?php echo $newsPost['news_link']; ?>
                        </td>
                        <td>
                            <?php echo $newsPost['news_title']; ?>
                        </td>
                        <!--td>
                            <div>
                                <datalist><//?php echo $newsPost['news_content']; ?></datalist>

                            </div>
                        </td-->
                        <td>
                            <img src="<?php  echo $newsPost['news_image'];?>" width="75" height="50"/>
                        </td>
                        <td>
                            <?php echo $newsPost['author']; ?>
                        </td>
                        <td>
                            <?php echo $newsPost['status']; ?>
                        </td>
                        <td>
                            <?php echo $newsPost['create_date']; ?>
                        </td>
                        <td>
                            <?php echo $newsPost['category']; ?>
                        </td>

                    </tr>



                <?php endforeach; ?>

Can you guys help me out the way can display image on page. I really appreciate it and thank you so much!



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi there,

One option to do so is to use the following approach by base64 encoding the blo:

<img src="data:image/jpeg;base64,<?php  echo base64_encode($newsPost['news_image']);?>" width="75" height="50"/>

However, you need to keep in mind that this is generally not a very good approach s it will put too much load on the initial request and slowing the entire page down.

A better approach would be to store in your database only the path to the image and upload your images to your public folder.

Hope that this helps. Regards, Bobby

To display a BLOB image stored in a database on your PHP webpage, you need to output the image data correctly in the HTML <img> tag. Here’s how you can modify your code to achieve this:


1. Storing Images Correctly

It looks like you’re storing the image directly as a BLOB. Ensure you’re storing the binary data (not just the file path or base64 string). You should be using something like file_get_contents() to retrieve and store the binary content of the uploaded image.


2. Modifying the Code to Display Images

You cannot directly use src="<?php echo $newsPost['news_image']; ?>" because the src attribute expects a URL or base64-encoded data, not raw binary data.

You need to:

  1. Create a PHP script to serve the BLOB image as a URL.
  2. Reference that script in the src attribute of the <img> tag.

Step-by-Step Solution

A. Create an Image Serving Script

Create a new file, e.g., display_image.php, to fetch and output the image from the database.

<?php
// Connect to the database
require 'db_connection.php'; // Adjust this to your connection file

// Check if an ID is provided
if (isset($_GET['id'])) {
    $id = intval($_GET['id']);
    
    // Query to fetch the image BLOB from the database
    $query = "SELECT news_image FROM news_post WHERE newsID = :id";
    $statement = $conn->prepare($query);
    $statement->bindValue(':id', $id, PDO::PARAM_INT);
    $statement->execute();
    $result = $statement->fetch(PDO::FETCH_ASSOC);

    if ($result) {
        // Output the image with the correct headers
        header("Content-Type: image/jpeg"); // Adjust based on your image type
        echo $result['news_image'];
    } else {
        // Handle no image found
        http_response_code(404);
        echo "Image not found.";
    }
    $statement->closeCursor();
} else {
    http_response_code(400);
    echo "Invalid request.";
}

B. Update the <img> Tag

Modify the src attribute in your table to point to this new script.

<td>
    <img src="display_image.php?id=<?php echo $newsPost['newsID']; ?>" width="75" height="50" />
</td>

3. Key Points to Check

  • Image Type: Ensure the correct MIME type (image/jpeg, image/png, etc.) is set in the header("Content-Type: ...") of display_image.php.
  • Database Field: Ensure the news_image field in your database contains valid binary image data.
  • Security: Validate and sanitize the id parameter to prevent SQL injection.
  • Performance: For better performance, consider storing images on a file system or cloud storage (e.g., AWS S3) and storing the file path or URL in the database instead of the binary content.

4. Testing

  • Ensure your database contains valid image BLOBs by manually verifying.
  • Test accessing display_image.php?id=1 (replace 1 with a valid newsID) in your browser to see if the image loads correctly.
  • If an error occurs, check your PHP error logs or enable debugging to identify issues.

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.