How to display an BLOB image stored in MySql database?

How to display an BLOB image stored in MySql database?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Displaying a Gallery of BLOB Images from MySQL

Displaying multiple images stored as Binary Large Objects (BLOBs) in a MySQL database requires shifting your mindset from simple file system operations to binary data handling. While displaying a single image is straightforward, rendering a gallery—specifically the last 5 uploads—introduces specific queries and output buffering considerations that are easy to overlook if you are transitioning from basic CRUD operations.

The core challenge lies in retrieving multiple rows of binary data and presenting them without corrupting the HTML response or triggering a download instead of an inline display. When you execute a query to fetch a list of images, you must ensure the database driver returns the BLOB column as raw bytes, not escaped strings, so that echo or output buffering can render them correctly.

Retrieving the Last Five Images

To achieve a gallery view, your PHP logic needs to replace a single-point lookup with an ordered aggregation. Using modern MySQL syntax, you would construct a query that orders results by timestamp and limits the result set. For example:

$limit = 5;
$sql = "SELECT id, name, image FROM store ORDER BY uploaded_at DESC LIMIT $limit";
$stmt = $pdo->query($sql); // Using PDO for safety
$images = $stmt->fetchAll(PDO::FETCH_ASSOC);

Notice the use of ORDER BY and LIMIT. This ensures you are consistently showing the most recent uploads. If your legacy code uses mysql_* functions as seen in your source material, this step remains critical but requires careful attention to escaping variables before binding them to queries to prevent SQL injection.

Handling Binary Output Correctly

A common pitfall when iterating over a gallery is mixing binary data with HTML text without proper delimiters. If you simply loop through the array and echo each image source immediately, browser rendering can fail if the headers are not set correctly or if the output buffer contains mixed content.

In your existing get.php, you correctly set the Content-type: image/jpeg header before echoing the binary data. However, when displaying multiple images in a gallery, it is often cleaner to let the database driver handle the type detection or explicitly define the MIME type based on file extensions if stored as generic BLOBs.

When iterating through your $images array, construct an HTML loop that wraps each image in a container:

<div class="gallery-grid">
    <?php foreach ($images as $img): ?>
        <div>
            <a href="/get.php?id=<?php echo htmlspecialchars($img['id']); ?>" target="_blank">
                <img src="/get.php?id=<?php echo htmlspecialchars($img['id']); ?>" alt="<?php echo htmlspecialchars($img['name']); ?>">
            </a>
        </div>
    <?php endforeach; ?>
</div>

This approach separates the retrieval logic from the presentation. By linking to a dedicated get.php script for each image, you maintain consistency in how images are served. This allows you to centralize header management and content-type detection in one place, ensuring that every image is served with the correct Content-Type regardless of how it was stored in the database.

Security Considerations for BLOB Storage

It is important to address the security implications inherent in your current implementation. Storing images directly into a database as BLOBs is generally discouraged in production environments because it mixes unstructured binary data with structured relational data, complicating backups and migrations. Furthermore, your upload code uses addslashes on the image content before inserting it. This is a dangerous practice for binary data; addslashes interprets single quotes as escape characters, which can corrupt image files (making them unreadable) or, worse, introduce SQL injection vulnerabilities if the resulting string contains quote characters that alter the SQL structure.

Instead of modifying the binary stream with string escaping functions, rely on prepared statements. Prepared statements handle the data separation between SQL logic and values, ensuring that even if a BLOB contains characters that look like SQL code, they are treated strictly as data bytes.

Moving Towards Modern Standards

If you are building this project for practice, consider how this pattern scales. As your application grows, managing binary blobs in MySQL can become a performance bottleneck due to the size of the data and the overhead of reading/writing large columns during transactions.

For larger-scale applications, frameworks like Laravel provide robust utilities to handle file uploads and storage, often decoupling the image storage from the database entirely by saving files to disk or cloud storage (like S3) while keeping only metadata in the database. If you are looking to modernize this practice project, exploring how Laravel handles Storage facades can be a valuable exercise. For more details on implementing robust storage solutions with Laravel, check out their documentation at https://laravelcompany.com. Transitioning from raw BLOB manipulation to managed storage patterns will not only improve security but also simplify your database schema maintenance as you add features like image resizing or version control.

Our network