how to Display Multiple Images (blob) from mysql using php?

13,264

Solution 1

A possible way to solve this problem is to have a separate script to dynamically output the contents of the image eg. :

image.php

header('Content-type: image/jpg');

// DataBase query and processing here...

echo $data['myImage'];

and call it whenever you need to show images stored in your DB eg. inside your loop:

echo '<img src="image.php?id=' . $data['id'] . '">';

But storing images in the database will take a toll on your server and unless they're really small or you have a good reason to do so, you should only store their physical location on the disk.

You can also use this approach if you wish to hide image location from your users, or control access, but there are better and faster alternatives for that case.

Solution 2

Just to mention the possibility to embed the images directly in html by encoding them, you can use this:

$query = "SELECT myImage FROM image";
if ($result = mysqli_query($link, $query)) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<img src="data:image/jpg;base64,' . base64_encode($row['myImage']) . '">';
    }
}

Pro:

  • The browser does not need to load the images over an additional network connection
  • You can query and display multiple images in one request

Con:

  • If the image(s) are big and/or there will be many images, the page will be load slow
  • Encoding an image to base64 will make it about 30% bigger.

For more information about base encode images:

Share:
13,264
Houssam
Author by

Houssam

Updated on June 10, 2022

Comments

  • Houssam
    Houssam almost 2 years

    I'm trying to display multiple images using PHP and MySql database, even if using the while loop I don't get all of the images, I only get one, I mean the first one in the table. What's the problem ?

    I'm using a table ID_IMAGE (int, pk, auto increment) and myImage (blob)

    $query = mysql_query("SELECT myImage FROM image");
    while($data=mysql_fetch_array($query)) {
        header('Content-type: image/jpg');
        echo $data['myImage'];
    }
    
    • Your Common Sense
      Your Common Sense almost 13 years
      You have to learn HTML first, friend