简体   繁体   English

如何使用PHP在MySQL查询中根据结果显示图像

[英]How to display image depending of result in MySQL query, using PHP

I was wondering for some time, and searching the nets, for an efficient way of displaying an image dynamically using PHP, depending on the result of a query. 我想知道一段时间,然后在网上搜索,以找到一种有效的方法来根据查询结果使用PHP动态显示图像。 Per example, there is a field called "devicetype" in my asset table, and I would like to display a different icon depending on the type of device. 例如,资产表中有一个名为“ devicetype”的字段,我想根据设备的类型显示不同的图标。

Anyone could point me in the right direction? 任何人都可以指出正确的方向吗? I've been reading around and many articles recommend against inserting images into the DB. 我一直在阅读,很多文章建议不要将图像插入数据库。

Thanks! 谢谢!

You don't need to insert the images into the DB. 您无需将图像插入数据库。 Just check the value of the column in your table and then use the appropriate image source based on it. 只需检查表中列的值,然后基于该列使用适当的图像源即可。 Something like this: 像这样:

while( $row = mysql_fetch_assoc($result) ) {
     $src = '';
     switch( $row['devicetype'] ) {
          case 'device1':
              $src = 'img_for_device.jpg';
              break;
          case 'device2':
              $src = 'img_for_device2.jpg';
              break;
          default:
              $src = 'default.jpg';

      }
      ?><img src="<?php echo $src; ?>" /><?php
}

I would store image in your website folder ie "website/deviceimg/*". 我会将图像存储在您的网站文件夹中,即“ website / deviceimg / *”。 Then, depending on your sql statement, I would load corresponding image by its name. 然后,根据您的sql语句,我将通过其名称加载相应的图像。 For example, you might use devicetypes as image names. 例如,您可以使用设备类型作为映像名称。 Loading image is fairly easy: "< img src=' + devicetype + '.jpg' />" 加载图像非常容易:“ <img src ='+ devicetype +'.jpg'/>”

I'm not sure I fully understand your question but can't you upload all the images you're going to use on your server? 我不确定我是否完全理解您的问题,但是您不能在服务器上上传要使用的所有图像吗? I think that's better than storing the actual images in your DB. 我认为这比将实际图像存储在数据库中更好。

So your code will be something like this: 因此,您的代码将如下所示:

if (results[devicetype] == "A") {
    echo '<img src="images/A.png" />'
else if (results[devicetype] == "B") {
    echo '<img src="images/B.png" />'

您可以在数据库中插入指向图像文件的链接。

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

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