$perPage = 10; // number of posts to display on each page $page = (isset($_GET['page']) ? $_GET['page'] : 1); // current page number $offset = ($page - 1) * $perPage; // calculate the offset for the query $query = "SELECT * FROM posts LIMIT $perPage OFFSET $offset"; // execute query to get posts // display posts foreach($posts as $post) { // display post contents ... } // add pagination links $totalPages = ceil($totalPosts / $perPage); // calculate total number of pages for($i=1; $i<=$totalPages; $i++) { echo ''.$i.' '; }
use Pagerfanta\Adapter\PhpArrayAdapter; use Pagerfanta\Pagerfanta; $products = [ ['id' => 1, 'name' => 'Product 1', 'price' => 100], ['id' => 2, 'name' => 'Product 2', 'price' => 200], ['id' => 3, 'name' => 'Product 3', 'price' => 300], ... ]; $perPage = 12; // number of products to display on each page $page = (isset($_GET['page']) ? $_GET['page'] : 1); // current page number $adapter = new PhpArrayAdapter($products); $pagerfanta = new Pagerfanta($adapter); $pagerfanta->setMaxPerPage($perPage); $pagerfanta->setCurrentPage($page); // display products foreach($pagerfanta->getCurrentPageResults() as $product) { // display product details ... } // add pagination links $paginator = new TwbsPagination('pagination'); $paginator->setCurrentPage($pagerfanta->getCurrentPage()); $paginator->setTotalPages($pagerfanta->getNbPages());In example 1, we are using native PHP functions to create pagination for a blog. In example 2, we are using the Pagerfanta package library to create pagination for an e-commerce website. Pagerfanta provides a variety of adapters (for example, PDO, Doctrine, and ElasticSearch) that can be used to work with different data sources.