I am trying to display something after 3 rows from my database, but having a hard time to get this to work.
this is my code at the moment
<?php
$query = "SELECT * FROM articles ORDER BY id DESC LIMIT 6";
$stmt = $con->prepare($query);
$stmt->execute();
$num = $stmt->rowCount();
if ($num>0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
echo "DATA FROM DATABASE";
if (($num % 3) == 0) {
echo '<h1>code every 3 rows</h1>';
}
$num++;
}
}
// if no records found
else{
echo "no data found";
}
?>
Currently, this is outputting after every row 1 and 4.
I have tried the following.
if ($num % 3) {
echo '<h1>code every 3 rows</h1>';
}
$num++;
This outputs after rows 2 3 5
I am sure its something simple I’m over looking but any help in pointing me in the right direction would be great.
2
Answers
You can use
($num - 1) % 3 == 2
:Example:
output:
Or
$k % 3 == 2
if you do theecho
before:Your error can be found where you initialized
$num
. you set it to row count and start increasing the $num in the loop. You code should be refactor like so: