skip to Main Content

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


  1. 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 "$in";
    }
    

    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 "$itemn";
        if ($k % 3 == 2) {
            echo "---n";
        }
    }
    
    Login or Signup to reply.
  2. 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";
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search