Rendering BLOB Images in Dynamic HTML Divs
When building a listing page where multiple items are fetched from a database and rendered as individual cards or divs, it is common to store media directly within the database using BLOB (Binary Large Object) columns. In your specific case, you have an adsubm table where image data resides in the content, name, type, and size fields. The core challenge here is not just retrieving the binary data, but correctly formatting it so the browser renders it within a loop without breaking the HTML structure or exposing raw binary streams.
The primary issue in your current implementation lies in the HTTP header handling inside the PHP loop. You are currently executing header('Content-type: image/jpeg'); before echoing the HTML div. This causes two distinct failures. First, you cannot send an HTML response and a binary image stream simultaneously; the browser expects one specific content type per request. Second, because you are fetching multiple rows in a while loop, sending headers on every iteration will result in the headers being sent repeatedly or overwriting each other, which often leads to a "500 Internal Server Error" or a blank white screen.
To display the image within the HTML div for each row, you must treat the binary data as a string resource that can be embedded directly into the src attribute of an <img> tag. The standard approach is to use Base64 encoding or to output the binary data in a way that preserves the boundary between the HTML structure and the image bytes.
Since you mentioned keeping things simple for now, let's look at how to handle the binary output safely within the loop without switching to external files immediately. If the database column content actually holds the raw JPEG binary data (which it should), you do not need to set the header inside the loop if you are embedding the image via a Data URI scheme. However, if you intend to serve the raw bytes directly, you must handle the content type outside the loop or ensure the logic flows correctly for a single image request per view.
Given your requirement to display multiple images on one page simultaneously, the most robust method that avoids server configuration complexity is converting the BLOB to a Base64 string. This converts the binary data into an ASCII-safe string that can be safely printed inside an HTML attribute. Here is how you can modify your retrieval and output logic:
$Category = 'Specials';
$query = $pdo->prepare("SELECT * FROM adsubm WHERE CATEGORY LIKE ? ORDER BY DATE DESC");
$query->execute([$Category]); // Use parameter binding for safety
while($row = $query->fetch()) {
$Adtitle = $row['ADTITLE'];
$Desc = $row['DESCRIPTION'];
$Price = $row['PRICE'];
$Date = $row['DATE'];
// Process date formatting here...
// ... existing date logic ...
// Extract the BLOB and convert to Base64
$blob = $row['content'];
$base64Image = base64_encode($blob);
// Determine MIME type based on your 'type' column or assume JPEG if consistent
$mime = 'image/jpeg';
if ($row['type'] === 'png') {
$mime = 'image/png';
}
echo "
<div class='[ col-xs-12 col-sm-offset-2 col-sm-8 ]' style='margin-top: 10px'>
<ul class='event-list'>
<li>
<time datetime='$Date'>
<span class='day'>" . date("d", strtotime($Date)) . "</span>
<span class='month'>" . date("F", strtotime($Date)) . "</span>
<span class='year'>" . date("Y", strtotime($Date)) . "</span>
<span class='time'>ALL DAY</span>
</time>
<!-- Embed the Base64 string directly into the src attribute -->
<img alt='$Adtitle' src='data:$mime;base64,$base64Image'>
<div class='info'>
<h2 class='title'>$Adtitle</h2>
<p class='desc'>$Desc</p>
<ul>
<li style='width:50%;'><span class='fa fa-money'></span> $Price</li>
</ul>
</div>
</li>
</ul>
</div>";
}
This approach removes the need to set Content-Type headers inside the loop because the browser interprets the data: URI scheme automatically. The browser reads the MIME type specified after data:, followed by base64,, and then renders the binary data contained within the string as an image immediately.
Trade-offs and Considerations
While Base64 encoding is convenient for dynamic rendering, it does carry a performance penalty. Encoding the binary data increases the payload size by approximately 33%. If your images are large, this can slow down the initial page load, especially on mobile networks. Additionally, you lose the ability to leverage browser caching effectively for individual images unless you configure the server to cache distinct Base64 strings (which is difficult due to their unique nature).
For production applications where performance matters, the industry standard is to save the uploaded BLOB to a physical file on the server's filesystem and store only the file path in the database. You would then generate an absolute URL (e.g., /uploads/image.jpg) and use that in your src attribute. This allows browsers to cache images independently of the HTML page, significantly improving load times as the number of adverts grows.
However, if you are constrained by file storage limits or simply wish to keep everything within the database for simplicity, Base64 is a viable solution. Just ensure that the content column in your MySQL table is defined with sufficient size (e.g., LONGBLOB) to accommodate full-resolution images without truncation.