how to display images from database in php?

i write bellow code to display images from database

$qry = "select id from image";
$res = mysql_query($qry) or die(mysql_error());
while($row = mysql_fetch_array($res))
  echo "<img src=image.php?id='$row[0]'>";


$query = mysql_query("SELECT img FROM images WHERE id = ".$_GET['id']);
$row = mysql_fetch_array($query);
echo $row['img'];

but this will not work. it display blank image icon.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You also might use base64 encoding to build in the image. Like

<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAWgBaAAD/4gxYSUNDX1BST0ZJTEUAAQEAAAxITGlubwIQAAB..." />

UPDATE, base64 encoding example

You can do that easily:

$imageId = intval($_GET["id"]);

$query = mysql_query("SELECT img FROM images WHERE id = ". $imageId);
$row = mysql_fetch_array($query);

$mime = null;
// place $type init. here
if ($type=="pjpeg") // <<< where do you get $type btw?
    $mime = "image/jpeg";

$b64Src = "data:".$mime.";base64," . base64_encode($row["img"]);
echo '<img src="'.$b64Src.'" alt="" />';

Solution 2

jpeg is not a valid Content-Type, it should be image/jpeg

Solution 3

As above
+ be sure to pass the replace = true parameter to the header function.

header( 'Content-Type: image/jpeg', true );

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply