A maintainable paging script should validate the requested page, count rows with COUNT(*), calculate a non-negative offset, bind LIMIT and OFFSET as integers, and use an explicit ORDER BY so records appear in a stable order.
<?php
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT) ?: 1;
$page = max(1, $page);
$perPage = 10;
$total = (int) $pdo->query('SELECT COUNT(*) FROM student')->fetchColumn();
$totalPages = max(1, (int) ceil($total / $perPage));
$page = min($page, $totalPages);
$offset = ($page - 1) * $perPage;
$stmt = $pdo->prepare(
'SELECT id, name, class, mark FROM student ORDER BY id LIMIT :limit OFFSET :offset'
);
$stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
| Name | Class | Mark |
| Babby John | Four | 69 |
| Giff Tow | Seven | 88 |
| Crelea | Seven | 79 |
| Big Nose | Three | 81 |
| Reppy Red | Six | 79 |
| PREV | 1 2 3 4 | NEXT |
Now Check our new code: Bootsrap Paging Classes
We will be using several SQL functions to manage records. Ensure that you have Mysql PDO connection to database.
Also read the article on how to display data from MySQL table here. We will be
using some sql commands like sql limit, order by etc so you can refer them in
our sql section.
Now let us have one table with nearly 35 records. We will
use the student table for this and you can use code sample at the end of this
tutorial to download the MySQL dump file to create the table along with the
script.
| Script | Description |
|---|---|
| Paging Script | Php script part of basic paging script ( part II) |
| user choice | User can select number of records per page by selecting drop down list |
| Header control | Change the listing order by clicking the column header |
| Advance Paging | Advance paging script with outer and inner paging |
| Ajax Paging | Paging without reloading page by using Ajax |
| Delet Record | Ajax paging with record delete option |
| Demo | Example Description |
|---|---|
| Basic Paging | Demo of basic paging script |
| User Selection | Demo of user selection of number of records per page |
| Header Link | Sorting of paging records order by different column headers |
| Advance Paging | Inner and outer links for paging of records in advance paging script |
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| chirag | 08-04-2012 |
| it is nice tutorial.... | |
| sourav | 20-09-2012 |
| Very nice and easy | |
| Ashahmali | 20-08-2013 |
| Very good tutorial thank you boss! | |
| nikhil | 05-09-2014 |
| very nice tutorial !thanks | |
| Abshir Ducaale | 19-09-2014 |
| thanks..great tutorials | |
| BHARTI | 03-12-2014 |
| Thank you for lovely tutorial .... and it is so easy...loveit | |