PHP code example of rudra / pagination

1. Go to this page and download the library: Download rudra/pagination library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rudra / pagination example snippets




use Rudra\Pagination;

// Parameters: current page, items per page, total items count
$pagination = new Pagination(
    value: 3,    // Current page
    perPage: 10, // Items per page (LIMIT)
    count: 95    // Total records in database
);

// 1. Get SQL OFFSET
$pagination->getOffset();  
// int(20) -> calculated as (3 - 1) * 10

// 2. Get SQL LIMIT
$pagination->getPerPage(); 
// int(10)

// 3. Get array of page numbers for rendering links
$pagination->getLinks();   
// array(10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
// (ceil(95 / 10) = 10 pages)



// 1. Get raw data
$page    = $_GET['page'] ?? 1;
$perPage = 20;
$count   = $db->query("SELECT COUNT(*) FROM articles")->fetchColumn();

// 2. Initialize Pagination
$pagination = new Pagination($page, $perPage, $count);

// 3. Fetch records using calculated OFFSET and LIMIT
$articles = $db->query(
    "SELECT * FROM articles LIMIT {$pagination->getPerPage()} OFFSET {$pagination->getOffset()}"
)->fetchAll();

// 4. Get page numbers to render <ul> in your template
$pages = $pagination->getLinks();