Home >Database >Mysql Tutorial >How to Display MySQL BLOB Images in PHP?

How to Display MySQL BLOB Images in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-13 06:16:11204browse

How to Display MySQL BLOB Images in PHP?

PHP BLOB Image Display from MySQL

Background

Storing and retrieving images as binary large objects (BLOBs) in a MySQL database is a common technique. However, displaying these images can sometimes be challenging.

Solution

Inserting an Image:

  1. Use the file_get_contents function to read the image file into a variable.
  2. Use a PREPARED STATEMENT to insert the image data into the BLOB column of the database:
$query = "INSERT INTO products (image) VALUES(?)";
$stmt = $db->prepare($query);
$stmt->bind_param('s', $image);
$stmt->execute();

Displaying an Image:

  1. Retrieve the image data from the database using a PREPARED STATEMENT:
$query = "SELECT * FROM products WHERE id = ?";
$stmt = $db->prepare($query);
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_array();
  1. Encode the image data using base64_encode and display it as an tag:
echo '<img src="data:image/jpeg;base64,' . base64_encode($row['image']) . '"/>';

The above is the detailed content of How to Display MySQL BLOB Images in PHP?. 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