Home > Database > Mysql Tutorial > body text

How to Display BLOB Images from a MySQL Database?

Mary-Kate Olsen
Release: 2024-10-30 00:47:29
Original
668 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!