开发者

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

开发者 https://www.devze.com 2023-01-14 06:26 出处:网络
I was wondering for some tim开发者_JAVA技巧e, 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 fie

I was wondering for some tim开发者_JAVA技巧e, 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 i.e. "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" />'


You can insert a link to the image file in the DB.

0

精彩评论

暂无评论...
验证码 换一张
取 消