Jcode Jcode - 7 months ago 13
PHP Question

PHP For loop not producing output

simple php for loop, worked fine before the loop was added, but I want it to print 4 rows of 3 products. Problem is its putting all 12 items into a single row! Then it creates 3 more empty rows at the bottom of the page.

Added updated version of the code, figured it might help someone else, although it displays correctly I have to pull 15 records from the table.

<?php for($i = 0; $i < 4; $i++) { ?>
<div class="row products">
<?php while($product = mysqli_fetch_assoc($featured)) : ?>

<!-- product-->
<div class="col-md-4 col-sm-6">
<div class="product">
<div class="image">
<a href="#"><img src=" <?= "images/wheels/wheelphotos/". $product["bigpic"]; ?>" alt= "<?= $product["manufacturer"]; ?>" class="img-responsive"></a>
<div class="quick-view-button"><button type="button" onclick="quickModal(<?= $product["recid"]; ?>)" class="btn btn-default btn-sm">Quick view</button></div>
</div>
<div class="text">
<p class="brand"><a href="#"><?= $product["manufacturer"]; ?></a></p>
<h3> <a href="detail.html"><?= $product["diam"]; ?></a></h3>
<p class="price">$<?= $product["rrp"]; ?></p>
<button class="btn btn-default btn-sm btn-primary">Details</button>
</div>
</div>
</div>

<?php endwhile; ?>
</div>
<?php } ?>


<?php for($i = 0; $i < 4; $i++) { ?>
<div class="row products">
<?php
$j = 0;
while($product = mysqli_fetch_assoc($featured)) :
$j++;
if($j > 3 ){
break;
}
?>
<!-- product-->
<div class="col-md-4 col-sm-6">
<div class="product">
<div class="image">
<a href="#"><img src=" <?= "images/wheels/wheelphotos/". $product["bigpic"]; ?>" alt= "<?= $product["manufacturer"]; ?>" class="img-responsive"></a>
<div class="quick-view-button"><button type="button" onclick="quickModal(<?= $product["recid"]; ?>)" class="btn btn-default btn-sm">Quick view</button></div>
</div>
<div class="text">
<p class="brand"><a href="#"><?= $product["manufacturer"]; ?></a></p>
<h3> <a href="detail.php"><?= $product["diam"]; ?></a></h3>
<p class="price">$<?= $product["rrp"]; ?></p>
<button class="btn btn-default btn-sm btn-primary" href="detail.php">Details</button>
</div>
</div>
</div>

<?php endwhile; ?>
</div>
<?php } ?>

Answer

Your while loop is going to run for as many records as your query selected. If you need to get out of that loop after a certain number of records, you can use a variable to count how many times you've been through the loop, then break out of the while loop. Your for loop will go through its next iteration and print the "row" div, and the while loop will process the next couple of records until you break again.

Comments