0

I have a php script that is basically querying my database and providing details about each store, and including an image. The code pulls in the image fine, but currently if no image exists in the database, I have spacer image being inserted instead. Instead of using a spacer image though, is there a way for me to use a PHP 'if' statement inside of the php code to not render an image if the database has no image listed? Here is the basic query code:

<?php   
   if(strlen($query) >= $min_length){$query = htmlspecialchars($query); 
   $query = mysql_real_escape_string($query); 
   $raw_results = mysql_query("SELECT * FROM stores WHERE `TRAVEL` = '1' AND `STATE` = '$query'") or die(mysql_error());                                  
   if(mysql_num_rows($raw_results) > 0){
   while($results = mysql_fetch_array($raw_results)){

   echo "<table width='150' border='3'>
   <tbody><tr>
   <td>".$results['NAME']."<br>
   <img  align='left' src='images/images/".$results['IMAGE']."'> 
   </td>
   </tr></tbody>
   </table>";            
   }          
   }    else{ echo "No results were found";

   }           
   }    else{ echo " ".$min_length; }
?>

For the php if statement, I was thinking something along these lines:

<?php if ($results['IMAGE'] != '') {  ?>
<img src='images/icons/".$results['IMAGE']."' height="100" width="auto">
<?php }?>

2 Answers2

2

You're pretty close. Just use one more <?php ... ?> block in the img

<?php if ($results['IMAGE'] != '') {  ?>
  <img src='images/icons/<?php echo $results['IMAGE'] ?>' height="100" width="auto">
<?php }?>

You can use the alternative control flow syntax too. It reads a little nicer than spanning the { and } across multiple <?php tags

<?php if ($results['IMAGE'] != ''):  ?>
  <img src='images/icons/<?php echo $results['IMAGE'] ?>' height="100" width="auto">
<?php endif ?>

Shameless plug:

Generating HTML with PHP gets really ugly. At least in my opinion. To make the job a little nicer/easier, I made htmlgen, mirrored on packagist.

Mulan
  • 129,518
  • 31
  • 228
  • 259
  • heredoc syntax works "okay" as well for generating HTML if you don't want to include another library. – honerlawd Mar 30 '16 at 15:44
  • Thanks, but it does not seem to be working. Do I need to wrap the in quotes, or modify it since it is inside of the other php code? –  Mar 30 '16 at 15:45
1

Simply like this :

if(isset($results['IMAGE'])){

  echo "<table width='150' border='3'>
  <tbody><tr>
  <td>".$results['NAME']."<br>
  <img  align='left' src='images/images/".$results['IMAGE']."'>
 </td>";

}
KubiRoazhon
  • 1,759
  • 3
  • 22
  • 48
  • Wouldn't this however not post the table if an image is non-existent, I actually want to keep the table even if the image is not in the table. –  Mar 30 '16 at 20:31