views:

34

answers:

4

Hey there everyone.

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!

A: 

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

laurent-rpnet
This does not address the question at all.
Russell Dias
Why not? From the OP: `Anyone could point me in the right direction? I've been reading around and many articles recommend against inserting images into the DB.` and he can efficiently return the link in the query and display the image from it
laurent-rpnet
This would do the same job as doing a `switch` statement to find the right image name hardcoded into the program... and tbh in my opinion it is a lot better to return the image file name associated with the device from the DB than to hardcode it. The accepted answer works but is very limited as the OP will have to change it's program if he inserts a new device!
laurent-rpnet
+1  A: 

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' />"

Sorantis
+2  A: 

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
}
Cfreak
Thanks, I really like the way this works. Also, the first response would be useful since I do store the asset type as text instead of an id, so it would just be a case of appending that inside the img src url.Many thanks!
TuxMeister
A: 

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" />'
Coding District