Home >Database >Mysql Tutorial >How to Display Images Stored in a MySQL Database Using PHP and HTML?

How to Display Images Stored in a MySQL Database Using PHP and HTML?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-12 20:39:09602browse

How to Display Images Stored in a MySQL Database Using PHP and HTML?

Displaying Images from MySQL Database in HTML

In this scenario, the goal is to retrieve images from a MySQL database using PHP and display them in an HTML document's tag. Let's delve into the provided code and explore how to address the issue encountered.

The PHP script in the provided code successfully establishes a connection to the database and runs a SELECT query. However, it's important to note that the returned result from mysql_query() is not the actual image data itself. Instead, it's a resource that represents the result set of the query.

To display the image in the tag, you'll need to perform an additional step of retrieving the actual image data from the database. This can be achieved by creating a separate PHP script that accepts a unique identifier (e.g., id) as a parameter, executes a SELECT query to retrieve the image data, and returns the data in binary format.

For example, you could create a script named getImage.php as follows:

<?php
$link = mysqli_connect("localhost", "root", "", "dvddb");
$sql = "SELECT dvdimage FROM dvd WHERE id = ? ";
$result = mysqli_execute_query($link, $sql, [$_GET['id']]);
$image = mysqli_fetch_column($result);

header("Content-type: image/jpeg");
echo $image;
?>

Then, in your catalog.php script, modify the tag to use the getImage.php script as the source of the image data:

<body>
<img src="getImage.php?id=1" width="175" height="200" />
</body>

By doing this, when the tag is rendered, it will send a request to getImage.php with the id of the image you want to display. The getImage.php script will retrieve the image data from the database and output it in binary format, which will be displayed by the tag.

The above is the detailed content of How to Display Images Stored in a MySQL Database Using PHP and HTML?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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