Home > Database > Mysql Tutorial > body text

How to Display Images Stored in a Database Using PHP?

Mary-Kate Olsen
Release: 2024-11-09 17:54:02
Original
298 people have browsed it

How to Display Images Stored in a Database Using PHP?

Displaying Images from a Database in PHP: A Resolution

Displaying images from a database can be a daunting task for beginners, but it can be accomplished with ease. Here's a solution to the question raised:

The provided PHP code attempts to display an image from a database, but it merely prints the path to the image as "user-1.jpg." To correctly display the image, we need to fetch its binary contents from the database and embed them into the web page.

Here's an updated version of the code:

$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']) . '" />';
Copy after login

Explanation:

  • We establish a connection to the database.
  • We define the SQL query to retrieve the image's binary contents.
  • We execute the query and fetch the result as an associative array.
  • The 'image' field in the result array contains the binary data of the image.
  • We use the PHP function base64_encode() to convert the binary data into a string that can be embedded in the page.
  • The 'src' attribute of the 'img' tag is composed of a data URI that encapsulates the image data and its MIME type. This allows the browser to display the image directly.

By implementing this solution, you should be able to successfully display images from your database in your PHP web applications.

The above is the detailed content of How to Display Images Stored in a Database Using PHP?. 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