Displaying Images from Database using PHP
Retrieving and displaying images stored in a database can be a common task in web development. This question addresses the issue of displaying an image obtained from a database, but the user encounters difficulties displaying it correctly.
To rectify this issue, it is important to understand how images are typically stored in databases. They are usually stored as binary data, which needs to be encoded for display. One way to encode binary data for display is using Base64 encoding.
The provided solution demonstrates how to achieve this باستخدام PHP. It connects to the database, executes the SQL query, and retrieves the image data. The retrieved data is then encoded using the base64_encode() function, and the resulting encoded string is used as the source for the tag. This allows the image to be displayed correctly in the web browser.
Here's an example code snippet:
$db = mysqli_connect("localhost", "root", "", "DbName"); $sql = "SELECT * FROM products WHERE id = $id"; $sth = $db->query($sql); $result = mysqli_fetch_array($sth); echo '<img src="data:image/jpeg;base64,' . base64_encode($result['image']) . '"/>';
The above is the detailed content of How to Display Images from a Database Using Base64 Encoding in PHP?. For more information, please follow other related articles on the PHP Chinese website!