好的,我正在尝试显示4个随机图像并从数据库中显示它们。随机性似乎有效,但我不明白如何显示4种不同的结果。它只显示4次结果4次。如果您有任何反馈请告诉我,谢谢。
<div class="similar-entrees-section food-tabs">
<h3>Similar entrees</h3>
<?php if ($food['catId']=1):?>
<?php $random=$db->fetchRow("select * from foods where catId=1 ORDER BY RAND() LIMIT 4"); ?>
<div class="row">
<div class="col-xs-6 col-sm-3">
<a href="#" class="food-block">
<div class="food-img"><img src="img/menu-items/<?php echo $random['image'] ; ?>" class="img-responsive" alt=""></div>
<h5>Cheddar Omelet
+ Chicken Sausage <span class="chilly"></span> </h5>
</a>
</div>
<div class="col-xs-6 col-sm-3">
<a href="#" class="food-block">
<div class="food-img"><img src="img/menu-items/<?php echo $random['image'] ; ?>" class="img-responsive" alt=""></div>
<h5>Gluten Free Breaded
Chicken <span class="chilly"></span></h5>
</a>
</div>
<div class="col-xs-6 col-sm-3">
<a href="#" class="food-block">
<div class="food-img"><img src="img/menu-items/<?php echo $random['image'] ; ?>" class="img-responsive" alt=""></div>
<h5>Mesquite Grilled
Chicken Breast</h5>
</a>
</div>
<div class="col-xs-6 col-sm-3">
<a href="#" class="food-block">
<div class="food-img"><img src="img/menu-items/<?php echo $random['image'] ; ?>" class="img-responsive" alt=""></div>
<h5>Mesquite Grilled
Chicken Breast <span class="chilly"></span></h5>
</a>
</div>
</div>
<?php endif; ?>
答案 0 :(得分:0)
首先,您需要替换
<?php $random=$db->fetchRow("select * from foods where catId=1 ORDER BY RAND() LIMIT 4"); ?>
带
<?php
$res = $db->query("select * from foods where catId=1 ORDER BY RAND() LIMIT 4");
$images = $db->getAll($res);
?>
之后,在每张图片之前,而不是
<?php echo $random['image'] ; ?>
你应该使用
<?php echo $images[0]['image'] ; ?>
表示第一张图片
<?php echo $images[1]['image'] ; ?>
第二个......等等。
我还建议你使用html代码为每个图像设置一个循环,最终生成所有图像的html。看看如何循环结果的以下链接。
https://pear.php.net/manual/en/package.database.mdb.intro-fetch.php
答案 1 :(得分:-1)
fetchRow
应该排成一排,而不是一切?
然后你使用<?php echo $random['image'] ; ?>
,它会一次又一次地显示同一行。
您可能希望使用类似getAll()
(如果您使用的是PEAR)来获取所有结果然后循环它们。
也许就像这样
<div class="similar-entrees-section food-tabs">
<h3>Similar entrees</h3>
<?php if ($food['catId'] = 1): ?>
<?php $random = $db->getAll("select * from foods where catId = 1 ORDER BY RAND() LIMIT 4"); ?>
<div class="row">
<?php foreach ($random as $r) { ?>
<div class="col-xs-6 col-sm-3">
<a href="#" class="food-block">
<div class="food-img">
<img src="img/menu-items/<?php echo $r['image']; ?>" class="img-responsive" alt=""></div>
<h5>Cheddar Omelet + Chicken Sausage <span class="chilly"></span></h5>
</a>
</div>
<?php } ?>
</div>
<?php endif; ?>