0

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.

1
  • I would suggest dropping the extract($row); and use the values from the array directly instead. Commented Feb 12, 2023 at 10:22

2 Answers 2

3

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";
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

thanks that makes perfect sense; I have a habit of over thinking things. thanks again.
2

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";
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.