我有一个php脚本,它基本上是查询我的数据库,提供每个商店的详细信息,并包括一个图像。代码很好地插入了图像,但目前如果数据库中不存在图像,我会插入间隔图像。不过,如果数据库中没有列出图像,我有没有办法在PHP代码中使用PHP"if"语句来不渲染图像,而不是使用间隔图像?以下是基本查询代码:
<?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 }?>
您非常接近。只需在img
中再使用一个<?php ... ?>
块
<?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真的很难看。至少在我看来。为了让工作变得更好/更容易,我制作了htmlgen,镜像在packagist上。
简单如下:
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>";
}