循环不同的php数组来显示不同的元素

时间:2017-11-15 01:59:45

标签: php

我正在将内容打印到html页面,正在打印已发布的内容,我试图显示5个不同的条目。

<?php
       $sql2 = "SELECT * FROM $itemTable ORDER BY RAND() LIMIT 5";
       $selected = $db->query($sql2);
       ?>

                 <h3 class="like">Recommended</h3>
       <?php while($reccomendedItem = mysqli_fetch_assoc($selected)) :?>
         <p><?php echo $reccomendedItem['ProductName']; ?></p>
                 <ul id="example">

        <li><img src="images/pic11.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>
        <li><img src="images/pic10.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>
        <li><img src="images/pic9.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>
        <li><img src="images/pic8.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>
        <li><img src="images/pic7.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>

                 </ul>

         <?php endwhile; ?>

这会在productName中为每5个项目生成相同的信息。

1 个答案:

答案 0 :(得分:3)

见这里:http://php.net/manual/en/function.mysql-fetch-assoc.php

循环中应该只有1 <li>个标记。如果你把所有5个放在循环中,那么每次循环时它都会生成5个相同的副本。此外,<ul>标记应该在循环之外开始和结束,否则每次传递都会重新插入。

尝试:

<ul id="example">
  <?php while($reccomendedItem = mysqli_fetch_assoc($selected)) :?>
    <li><img src="images/pic11.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>
  <?php endwhile; ?>
</ul>