How to display image from database using php

How to display image from database using php

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

Stefan Bogdanescu

Founder & Senior Architect

Why user-1.jpg Appears Instead of Your Image and How to Fix It

When you query a database for an image path and simply print that string back into your view, you often see raw text like user-1.jpg rendered as characters on the screen rather than the actual picture. This happens because HTML treats plain text as literal content unless explicitly told otherwise. In your specific scenario, the code retrieves the filename stored in the database and outputs it using print. Without proper context, the browser interprets this output as a string variable to be displayed directly, not as a reference to a resource on the server.

To display an image correctly, you must instruct the browser to treat the output as an <img> tag source attribute or force the response header to indicate that the content is binary data (image) rather than text. The current implementation lacks the necessary HTML structure and HTTP headers to trigger this behavior.

Retrieving Safe Data from the Database

The first hurdle in your snippet is how the data is being fetched. You are using the mysql_ extension, which is deprecated as of PHP 5.5 and removed entirely in PHP 7.0. Continuing to use these functions introduces significant security risks and compatibility issues. Furthermore, constructing queries by concatenating variables directly into the SQL string—such as $id1 in your example—is vulnerable to SQL injection attacks.

You should migrate immediately to mysqli or PDO with prepared statements. If you are already on a modern stack like Laravel, using raw MySQL queries is unnecessary; the framework provides robust methods for interacting with the database that handle escaping and connection management automatically.

Here is how you would refactor the query using mysqli:

$stmt = $pdo->prepare("SELECT image FROM userdetail WHERE id = ?");
$stmt->execute([$id1]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row) {
    $imagePath = $row['image'];
} else {
    $imagePath = 'default-placeholder.jpg';
}

This approach ensures that the $id1 variable is properly escaped before being sent to the database engine, closing the door to injection vulnerabilities. Always verify that a row exists before accessing columns to prevent undefined index notices.

Rendering the Image Correctly

Once you have the image path stored in a variable like $imagePath, you cannot simply print or echo it. You need to wrap that string inside an HTML <img> tag. The browser's default behavior when seeing "user-1.jpg" is to render those six characters as text. To change this, construct the full URL including your server's base path and assign it to the src attribute.

In a PHP template or view file, the logic looks like this:

echo '<img src="' . htmlspecialchars($imagePath) . '" alt="User profile image">';

Using htmlspecialchars() is critical here. Even though you fetched the data from your own database, users might be able to modify records if your application has any write access points. If a malicious actor injects a script tag into the image filename field (e.g., <script>alert(1)</script>.jpg), echoing it directly would execute that script. Sanitizing the output ensures that special characters are converted to HTML entities, breaking any potential XSS payload.

Handling Binary Data and HTTP Headers

If your database column stores the actual binary image data (BLOB) rather than a file path string, the approach changes slightly. You must read the binary stream into memory or send it directly to the client using readfile(). When sending binary data, you must set the correct MIME type header before outputting anything else. If the server sends a text/plain header while trying to serve an image, the browser will download the file instead of displaying it, often resulting in the filename appearing in the address bar or error console.

header("Content-Type: image/jpeg"); // Or image/png depending on your data
echo $imageBinaryData;

However, storing binary data directly in a database table is generally inefficient for large images and makes resizing or caching difficult. The standard practice remains storing the file path (relative to your web root or an absolute URL) in the database and serving the file from disk via PHP's built-in static file handling when accessed through a URL route.

The Laravel Way

If you are building this application using the framework mentioned at https://laravelcompany.com, you can abstract these details away entirely. Laravel handles routing, view rendering, and asset management out of the box. You would typically store the image path in your Eloquent model and pass it directly to a Blade template:

// In Controller or Model
$user->profile_image = $request->get('image_path');

// In Blade View
<img src="{{ asset($user->profile_image) }}" alt="User Image">

The asset() helper function in Laravel ensures the path is prefixed with your application's base URL, making it accessible to the browser regardless of where the script resides. This pattern eliminates the need for manual header manipulation or raw HTML echoing, reducing the surface area for security errors and simplifying maintenance.

Our network