简体   繁体   English

如何使用php从mysql显示多个图像(blob)?

[英]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. 我正在尝试使用PHP和MySql数据库显示多个图像,即使使用while循环,我也无法获得所有图像,我只能得到一个图像,我的意思是表中的第一个图像。 What's the problem ? 有什么问题 ?

I'm using a table ID_IMAGE (int, pk, auto increment) and myImage (blob) 我正在使用表ID_IMAGE (int, pk, auto increment)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 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: 仅提及通过编码将图像直接嵌入html的可能性,您可以使用以下方法:

$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. 将图像编码为base64会使它大30%。

For more information about base encode images: 有关基本编码图像的更多信息:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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