Hi all, I am having trouble figuring out a good way to go about looping my database results. Currently, my code looks something like the following (abbreviated for simplicity):

$db_results = $wpdb->get_results("SELECT * FROM table");

echo '<table><thead><th>Name</th><th>Number</th></thead>';
echo '<tbody>';
foreach ($db_results as $result) {
    echo '<tr>';
        echo '<td>' .$result->name. '</td>';
        echo '<td>' .$result->number. '</td>';
    echo '</tr>';
}
echo '</tbody></table>';

This is working great, except I am using this page for printing purposes, and when the table runs past the end of the page, sometimes the printing stops dead in the center of one <tr>, and continues the second half of the <tr> on the next page.

What I would like is to have the table display no more than 40 rows (the number that can fit on my size paper), then close the <table>, re-open the <table> with a new <thead> and everything, and display 40 more rows, and continue this way.

I have tried a different combination of while, do - while and for statements, none of which are working for me.

If anyone could help me out with a code snippet on how to do this I would be eternally greatful!

Thanks in advance, gurus!

I haven't tested this, but it should give you an idea of how to modify your existing loop to include the page breaks.

$db_results = $wpdb->get_results("SELECT * FROM table");

$counter = 0;
foreach ($db_results as $result) {
    if ($counter % 40 === 0)
        echo '<table><thead><th>Name</th><th>Number</th></thead><tbody>';

    echo '<tr>';
        echo '<td>' .$result->name. '</td>';
        echo '<td>' .$result->number. '</td>';
    echo '</tr>';

    $counter++;
    if ($counter % 40 === 0)
        echo '</tbody></table>';
}
echo '</tbody></table>';

Thank you so much Hearth!! I tried for a solid hour with no results, and your "untested" code worked right away with no modification. I knew it was simple!

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.