ChrisMe
ChrisMe

Reputation: 55

php insert image after every 3rd result

I have a table with 7 entries and in future there will be added more. I need to insert an image after every 3rd result from table. Currently it would be 2 images, but later it can be more.

$sqlSelect = "SELECT name,rank,points FROM `users` WHERE rank = 1";
$data = $db->query($sqlSelect);

foreach ($data as $row) {
    $name = $row['name']; 
    $rank = $row['rank']; 
    $pts = $row['points']; 

    echo '<a href="/' . $name . '" title="' . $name . '">;
    echo $name . ' | ' .  $rank . ' | ' .  $pts . '</a>';
}

Would this work?

count(*) AS count
$cnt = $row['count']; 

Then put that into for loop. But I can't figure out what do I write in the for loop.

for ($x = 3; $x == $cnt; $x++) {
    if ($x == 3) {
        echo "The number is: $x <br/>";
    }
}

How do I add +3 to the X instead of X++ ?

Upvotes: 1

Views: 81

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Problem

I need to insert an image after every 3rd result from table.

Solution

You can use a simple variable, like $counter to display an image after every third row, like this:

<?php 

    $sqlSelect = "SELECT name,rank,points FROM `users` WHERE rank = 1";
    $data = $db->query($sqlSelect);

    $counter = 1;  // to keep track of number of rows
    foreach ($data as $row) {

        if($counter % 4 == 0){
            // display image here
        }
        ++$counter;

        $name = $row['name']; 
        $rank = $row['rank']; 
        $pts = $row['points']; 

        $path = '<a href="/' . $name . '" title="' . $name . '">';
        $path .= $name . ' | ' .  $rank . ' | ' .  $pts . '</a>';
        echo $path;

    }
?>

And it'll be an overkill to execute a separate query to count the number of rows.

Upvotes: 1

Related Questions