在php代码中插入php if语句?

时间:2016-03-30 15:28:21

标签: php

我有一个php脚本,基本上是查询我的数据库并提供有关每个商店的详细信息,包括图像。代码可以很好地提取图像,但是目前如果数据库中没有图像,我会插入间隔图像。不过使用间隔图像,我有没有办法使用PHP'如果'如果数据库没有列出图像,PHP代码内部的语句不呈现图像?这是基本的查询代码:

<?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; }
?>

对于php if语句,我在思考这些问题:

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

2 个答案:

答案 0 :(得分:2)

你非常接近。只需在<?php ... ?>

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

您也可以使用备用控制流语法。它比多个{标记中的}<?php更好看

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

无耻插件:

使用PHP生成HTML变得非常难看。最起码,我是这么想的。为了使工作变得更好/更容易,我做了naomik/htmlgen

答案 1 :(得分:1)

就像这样:

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>";

}
相关问题