Nashie
Nashie

Reputation: 331

PHP while loop echo every 3 rows

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.

Upvotes: 0

Views: 83

Answers (2)

Wisdom Ighofose
Wisdom Ighofose

Reputation: 357

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:

<?php 
$query = "SELECT * FROM articles ORDER BY id DESC LIMIT 6";
$stmt = $con->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();

//$num should start from 1 and increase in the loop
$num = 1;
if($count>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";
}
?>

Upvotes: 3

Syscall
Syscall

Reputation: 19780

You can use ($num - 1) % 3 == 2:

if (($num - 1) % 3 == 2) {
   echo '<h1>code every 3 rows</h1>';
}
$num++;
echo "DATA FROM DATABASE";

Example:

foreach (range(0, 6) as $k => $i) {
    if (($k - 1) % 3 == 2) {
        echo "---\n";
    }
    echo "$i\n";
}

output:

0
1
2
---
3
4
5
---
6

Or $k % 3 == 2 if you do the echo before:

foreach (range(0, 6) as $k => $item) {
    echo "$item\n";
    if ($k % 3 == 2) {
        echo "---\n";
    }
}

Upvotes: 2

Related Questions