Pagination with a PHP class

David Carr

PHP & MySQL Tutorials Development

I've recently wrote a pagination class for php, I used to do this in a procedural way by using functions, it's always worked fine, but its not as reusable as a class is.

I've released this class on Github this tutorial will explain how to use the pagination class.

  • Include the class
  • Create a new instance of the class, set the number of records by page and a reference
  • Then set the total number of records, do this by either setting in manually or by counting records from a dataset
  • Then display the records as normal
  • To show the page links echo page_links() optionally passin 2 parameters the first set the address by default this is ? the second parameter is for any $_GET's you want to pass from page to page.
//include the class
include('paginator.php');

//create new object pass in number of pages and identifier
$pages = new Paginator('10','p');

//get number of total records
$stmt = $db->query('SELECT count(id) FROM table');
$row = $stmt->fetch(PDO::FETCH_NUM);
$total = $row[0];

//pass number of records to
$pages->set_total($total); 

$data = $db->query('SELECT * FROM table '.$pages->get_limit());
foreach($data as $row) {
    //display the records here
}

//create the page links
echo $pages->page_links();

Download the class from Github

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.