简体   繁体   中英

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

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'];
}

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM