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

后端 未结 2 681
栀梦
栀梦 2021-01-16 03:16

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 fir

相关标签:
2条回答
  • 2021-01-16 04:07

    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.

    0 讨论(0)
  • 2021-01-16 04:13

    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:

    • http://davidbcalhoun.com/2011/when-to-base64-encode-images-and-when-not-to/
    • base64 encoded image size
    0 讨论(0)
提交回复
热议问题