简体   繁体   中英

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. 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.

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/*". Then, depending on your sql statement, I would load corresponding image by its name. For example, you might use devicetypes as image names. Loading image is fairly easy: "< 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" />'

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

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