Pagination in PHP

Hello! I was looking for a normal article on the Internet on how to write pagination in PHP with my own hands, but, alas, I did not find normal material on this topic. (( Can you elaborate on how this can be implemented?! Thanks in advance!

Answer 1, authority 100%

$page = (!empty($_GET['page']))?$_GET['page']:1;
if ($page < 1) $page = 1;
$per_page = 50;

Next, look for a query that returns records and do something like this:

$count = 0;
$count_res = mysql_query('SELECT COUNT(ID) as C FROM main_table WHERE [...];');
if ($count_db = mysql_fetch_object($count_res))
  $count = $count_db->C;
$total_pages = ceil($count / $per_page);
if ($page > $total_pages)
  $page = $total_pages;

Here we found the current page, taking into account the number of records in the database, the number of records and the number of pages. Next, the actual editing of the request:

$records_res = mysql_query('[...] LIMIT '.(($page-1)*$per_page).', '.$per_page.';');

We got the records of the current page.
Links to pages:

for ($i = 1; $i <= $total_pages; $i++) {
  if ($i != $page) {
    echo '<a class="page" href="?page='.$i.'">'.$i.'</a>';
    } else echo $i;

Answer 2, authority 33%

What do you mean by “pagination”?

If, for example, you need to output 1000 photos from the database, say 10 per page, then this is done using the database itself with the construction

  • LIMIT 0,10– first page.
  • LIMIT 10,10– second page.
  • LIMIT 20,10– third page.


If you need to somehow display those same pages (ie, navigation through these pages, then I recommend google on the topic “php pagger”) or write something similar yourself. There is nothing complicated about this.