We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,586 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Looping question

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!

2
Contributors
2
Replies
9 Hours
Discussion Span
1 Year Ago
Last Updated
3
Views
Question
Answered
drumichael87
Light Poster
42 posts since Jun 2009
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

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>';
Hearth
Posting Whiz
319 posts since Apr 2008
Reputation Points: 123
Solved Threads: 49
Skill Endorsements: 4

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!

drumichael87
Light Poster
42 posts since Jun 2009
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0
Question Answered as of 1 Year Ago by Hearth

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.0683 seconds using 2.67MB