PHP foreach loop Pagination not working

I have a foreach loop that pulls data from my database (members profiles), I want to paginate these so that they do not all load at once and are easier to browse.

My initial idea was a load more button rather than typical numbered pagination.

I’ve managed to limit the results based on page number (I’m still not sure if that code is perfect either) but I can’t appear to get page numbers to display, currently it is just outputting the limit I’ve set - how can I amend the pagination so that it displays page numbers based on the limit set per page?

For example if there are ten results and the limit per page is five, I’d see 1, 2 as links in the pagination.

Foreach loop code (minus HTML);


  $nItemsPerPage = 2;
  $page = isset($_GET['page'])?$_GET['page']:1;

  foreach(array_slice($members_with_locations_homepage, $nItemsPerPage*($page-1), $nItemsPerPage) as $members_with_location_homepage): ?> 


  <?php endforeach; ?> 

HTML for rendering pagination;

<ul id='paginator'>
for($i=1;$i<$nItemsPerPage;$i++) { ?>
    <li><a href='?page=<?php echo $i; ?>'><?php echo $i ?></a></li>
<?php } ?>

Don’t you need to get a total count, and divide your $nItemsPerPage into that figure? Right now you’re running a loop up to the number of items per page, not the number of pages.

Yes, you are right I think I do… I do have a function for that already for use elsewhere… but I don’t know how to write the division stuff that will spread the result set across multipe pages.

The way I’d do it is to run two queries. The first would get the total count of rows available, the second would retrieve just the page of rows I wanted. That would be based on a start position of (page number * rows per page) and limited to rows-per-page. There may be some subtracting so you can use base-1 page numbers, or maybe adding a number for display, just because normal people don’t like page zero.

You can always use a bit of JavaScript to retrieve the “next x rows” and add them to the end of your page, for the “more results” option.

It seems a bit wrong somehow to run two queries, but I suspect running a count and then just retrieving a single page of rows is probably quicker than retrieving all the rows, using rowcount from the results, and then just displaying part of the result set.

1 Like

if someone build it’s database structure properly, the database will only use the index to dertermine the count, and without returning actual data, this is pretty fast.

I like this “probably”

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.