Home  >  Article  >  Database  >  How to Display BLOB Images from a MySQL Database?

How to Display BLOB Images from a MySQL Database?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 00:47:29669browse

How to Display BLOB Images from a MySQL Database?

Displaying BLOB Images from MySQL Database

To retrieve and display BLOB images stored in a MySQL database, follow these steps:

1. Retrieve the Image Data:

Connect to the database and execute a query using the SELECT statement to retrieve the image data from the BLOB field. For example:

<code class="sql">SELECT id, image FROM store ORDER BY id DESC LIMIT 5;</code>

2. Loop Through the Results:

Use a loop to iterate through each row of the query results.

3. Display the Image:

For each row, you can display the image by:

  • Encoding the BLOB data using [base64_encode()](https://www.php.net/manual/en/function.base64-encode.php).
  • Embedding the encoded data in an tag as the src attribute. For example:
<code class="html">echo "<img src='data:image/jpeg;base64," . base64_encode($image) . "' />";</code>

Example Code:

The following code demonstrates how to display the last 5 uploaded images from a MySQL store table:

<code class="php">$sql = "SELECT id, image FROM store ORDER BY id DESC LIMIT 5";
$result = mysqli_query($db, $sql);

while($row = mysqli_fetch_array($result)) {
    echo "<img src='data:image/jpeg;base64," . base64_encode($row['image']) . "' />";
}</code>

Additional Notes:

  • Ensure that the Content-Type header is set to image/jpeg when displaying the image.
  • Consider optimizing the image retrieval process by using caching techniques.

The above is the detailed content of How to Display BLOB Images from a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn