user2375199
user2375199

Reputation: 13

div's with each 6 results in it PHP MYSQL

<div>
<?php   if ($result->num_rows > 0) { 
$i=1;
while($row = $result->fetch_assoc()) { 

        if( $i % 6 == 0 )
        { ?>        
            </div>
            <div>
    <?php } ?>
    <h4><?php echo $row["city"] ?></h4>
    <h6><?php echo $row["info"] ?></h6>
<?php   $i++;
}
} else {
echo "0 results";
}
?>
</div>

Goal: div's with each 6 rows in it. When I use $i=1, the first gets 5 results and the other ones get 6. When I use $i=0 the first one is empty and the other ones get 6.

How to get the first div also filled with 6 results?

Upvotes: 0

Views: 78

Answers (3)

Justinas
Justinas

Reputation: 43507

Try using array_chunk. That way you don't have to worry where to put your div ends and it's more readable:

$rows = [];
while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}

foreach (array_chunk($rows, 6) as $subset) {
    echo "<div>";
    foreach ($subset as $row) {
        echo "<h4>{$row["city"]}</h4>"
        echo "<h6>{$row["info"]}</h6>"
    }
    echo "</div>";
}

Upvotes: 4

lolbas
lolbas

Reputation: 794

Using array_chunk as proposed by @Justinas is a good way to refactor code. Yet, taking your original code, the issue is about where you check printed amount. It is wrong to first check output amount as it breaks the logic for the first iteration. Please, refer to the code below.

<div>
<?php

if ($result->num_rows > 0) { 
    $i = 1;
    while ($row = $result->fetch_assoc()) {
        # if ($i % 6 == 0) {     
        #     echo '</div><div>';
        # }
        # move commented code from above to ...

        echo "<h4>{$row["city"]}</h4>";
        echo "<h6>{$row["info"]}</h6>";

        # ... here
        if ($i % 6 == 0) {     
            echo '</div><div>';
        }

        $i++;
    }
} else {
    echo "0 results";
}
?>
</div>

Upvotes: 1

Pandraghon
Pandraghon

Reputation: 62

You can try setting $i = 0 then excluding it in your if statement with

if ($i > 0 && $i % 6 == 0) 

since 0 % 6 == 0.

Upvotes: 0

Related Questions