Hello Everyone,

I am trying to pull some info from a MySQL database. The problem is that, for every four rows that are fetched, I need to add a div tage before and after, so here is an example of what I want:

This is the static way I have at the minute:

<div id="shelf" class="Magenta_div">
<img src="_images/covers/Magenta/L1/L1-1.png" alt="Cover" id="book_toggle" class="cover" title="Monkey Fun" onclick="alert('Book not completed')" />
<img src="_images/covers/Magenta/L1/L1-2.png" alt="Cover" id="book_toggle" class="cover" title="I Am a Robot" onclick="alert('Book not completed')" />
<img src="_images/covers/Magenta/L1/L1-3.png" alt="Cover" id="book_toggle" class="cover" title="What Next?" onclick="alert('Book not completed')" />
<img src="_images/covers/Magenta/L1/L1-4.png" alt="Cover" id="book_toggle" class="cover" title="Sleeping Animals" onclick="alert('Book not completed')" />
</div>

But obviously there are more than four books, so I need to loop throught the databse getting each image:

<img src="_images/covers/Magenta/L1/L1-4.png" alt="Cover" id="book_toggle" class="cover" title="Sleeping Animals" onclick="alert('Book not completed')" />

and for every four I need to add

<div id="shelf" class="Magenta_div">

Before and

</div>

after.

I thought I found a solution to the problem using multiples of four, however, if the total number of rows was not a multiple of four, then the end divs were getting put in too often and the page was screwing up.

Thank you for your time,

Daniel

The following code should roughly do it:

// add the first div
echo '<div id="shelf" class="Magenta_div">';

// initialize the counter for the current table row
$current_row = 1;

while($row = mysqli_fetch_row($res)) {

    // echo the image data from  the db table row
    echo "...";

    // check if the current row count is divisible by 4
    // if yes end the div and add another div
    if($current_row % 4 == 0) {

        echo '</div>';
        echo '<div id="shelf" class="Magenta_div">';
    }

    // increase the current row
    $current_row++;
}

// add the last div
echo '</div>';

The only thing is that in the last div you can have 0 images but you can check the number of rows returned and if it is divisible by 4 do not echo the last <div> </div> pair of tags.

You my friend are a genius, that you very much for your time and effort. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.