How to Display Images from a Database Using PHP?
Nov 06, 2024 am 09:23 AMDisplaying 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'] ).'"/>';
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 <img> 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Reduce the use of MySQL memory in Docker

How do you alter a table in MySQL using the ALTER TABLE statement?

How to solve the problem of mysql cannot open shared library

Run MySQl in Linux (with/without podman container with phpmyadmin)

What is SQLite? Comprehensive overview

Running multiple MySQL versions on MacOS: A step-by-step guide

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)?

How do I configure SSL/TLS encryption for MySQL connections?
