Home > Database > Mysql Tutorial > How to Display Images from a Database Using PHP?

How to Display Images from a Database Using PHP?

Susan Sarandon
Release: 2024-11-06 09:23:02
Original
724 people have browsed it

How to Display Images from a Database Using PHP?

Displaying Images from Database Using PHP

In PHP, displaying images stored in a database is a common task. Let's explore a code snippet to accomplish this:

$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

This code utilizes the MySQL database extension (mysqli) to retrieve image data from a database and then employs base64 encoding to display the image as an inline HTML element. Here's what each section of the code does:

  • Database Connection: First, a connection to the database is established using the mysqli_connect function.
  • SQL Query: An SQL query is executed to fetch the image data from the products table based on a given id.
  • Data Retrieval: The image data is retrieved from the query result.
  • Image Encoding: The image data is converted to a base64 string using base64_encode.
  • Image Display: A HTML element is generated to display the image using the base64 encoded data as the source.

By implementing the provided code, you can successfully display images stored in a database on your web page.

The above is the detailed content of How to Display Images from 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