Home >Database >Mysql Tutorial >Why Is My MySQL BLOB Image Not Displaying Correctly?
Displaying Images Stored as BLOBs in MySQL
Seeking to retrieve images stored as BLOBs in a database, you encounter difficulties in displaying them correctly. Your code retrieves the data and passes it to a script that sets the header to image/jpeg and echoes the image. However, you observe an image icon but not the image itself in the browser.
To resolve this issue, it is suggested you employ a modified approach:
Insert Images into the Database
// Retrieve image data from a temporary file $image = file_get_contents($_FILES['images']['tmp_name']); // Prepare an SQL statement and bind the image parameter $query = "INSERT INTO products (image) VALUES(?)"; $stmt = $db->prepare($query); $stmt->bind_param('s', $image); // Execute the statement $stmt->execute();
Retrieve and Display Images from the Database
// Prepare an SQL statement and bind the ID parameter $sql = "SELECT * FROM products WHERE id = ?"; $stmt = $db->prepare($sql); $stmt->bind_param('s', $id); // Execute the statement and retrieve the result $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_array(); // Encode the image data as base64 and embed it in an HTML element echo '<img src="data:image/jpeg;base64,' . base64_encode($row['image']) . '" />';
This revised approach should enable you to display images stored as BLOBs in MySQL effectively. By binding the image parameter and encoding it as base64 within the HTML element, you can correctly retrieve and present the image data.
The above is the detailed content of Why Is My MySQL BLOB Image Not Displaying Correctly?. For more information, please follow other related articles on the PHP Chinese website!