Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve images from MySQL database and display in an html tag

Tags:

html

php

mysql

I created a MySQL database with a table using phpmyadmin. I created this table with a BLOB column to hold a jpeg file.

I have issues with regards to the php variable $result here.

My code so far: (catalog.php):

<body> <?php   $link = mysql_connect("localhost", "root", "");   mysql_select_db("dvddb");   $sql = "SELECT dvdimage FROM dvd WHERE id=1";   $result = mysql_query("$sql");   mysql_close($link);  ?> <img src="" width="175" height="200" /> </body> 

How can I get the variable $result from PHP into the HTML so I can display it in the <img> tag?

like image 879
exxcellent Avatar asked Oct 17 '11 11:10

exxcellent


People also ask

How can we retrieve image from database and display in HTML?

php $id = $_GET['id']; // do some validation here to ensure id is safe $link = mysql_connect("localhost", "root", ""); mysql_select_db("dvddb"); $sql = "SELECT dvdimage FROM dvd WHERE id=$id"; $result = mysql_query("$sql"); $row = mysql_fetch_assoc($result); mysql_close($link); header("Content-type: image/jpeg"); echo ...

How show data from MySQL in HTML?

First, connect to the database: $conn=mysql_connect("hostname","username","password"); mysql_select_db("databasename",$conn); You can use this to display a single record: For example, if the URL was /index.

How do I display images in MySQL database?

php $connection =mysql_connect("localhost", "root" , ""); $sqlimage = "SELECT * FROM userdetail where `id` = '". $id1. "'"; $imageresult1 = mysql_query($sqlimage,$connection); while($rows = mysql_fetch_assoc($imageresult1)) { echo'<img height="300" width="300" src="data:image;base64,'.


2 Answers

You can't. You need to create another php script to return the image data, e.g. getImage.php. Change catalog.php to:

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

Then getImage.php is

<?php    $id = $_GET['id'];   // do some validation here to ensure id is safe    $link = mysql_connect("localhost", "root", "");   mysql_select_db("dvddb");   $sql = "SELECT dvdimage FROM dvd WHERE id=$id";   $result = mysql_query("$sql");   $row = mysql_fetch_assoc($result);   mysql_close($link);    header("Content-type: image/jpeg");   echo $row['dvdimage']; ?> 
like image 178
daiscog Avatar answered Oct 05 '22 23:10

daiscog


Technically, you can too put image data in an img tag, using data URIs.

<img src="data:image/jpeg;base64,<?php echo base64_encode( $image_data ); ?>" /> 

There are some special circumstances where this could even be useful, although in most cases you're better off serving the image through a separate script like daiscog suggests.

like image 26
Ilmari Karonen Avatar answered Oct 06 '22 01:10

Ilmari Karonen