PHP Pagination with Bootstrap 3

In this guide, I will show you how to create a very simple pagination in PHP using Bootstrap 3.

With just a few steps you will be able to create something like this:


Before we start, prepare the following files and folders:
- bootstrap/
- index.php
- pagination.php

Step 1:

Download Bootstrap 3 and extract its content inside bootstrap directory:

- bootstrap/
├── css/
│   ├── bootstrap.css
│   ├── bootstrap.min.css
│   ├── bootstrap-theme.css
│   └── bootstrap-theme.min.css
├── js/
│   ├── bootstrap.js
│   └── bootstrap.min.js
├── fonts/
│   ├── glyphicons-halflings-regular.eot
│   ├── glyphicons-halflings-regular.svg
│   ├── glyphicons-halflings-regular.ttf
│   └── glyphicons-halflings-regular.woff
- index.php
- pagination.php

Step 2:

Copy the basic template and paste it in index.php.

Step 3:

Remove the line:

<h1>Hello, world!</h1>

And replace with:

<div class="container">
    <div class="row">
        <?php require 'pagination.php'; ?>
    </div>
</div>

Pagination

Now for the pagination, let's start by creating a sample data.

I picked some books from Good Reads and stored it as an array to the variable $bookshelf

$bookshelf = array(
    0 => 'Do Androids Dream of Electric Sheep?',
    1 => 'The Curious Incident of the Dog in the Night-Time',
    2 => 'The Hollow Chocolate Bunnies of the Apocalypse',
    3 => 'To Kill a Mockingbird',
    4 => 'The Unbearable Lightness of Being',
    5 => 'Midnight in the Garden of Good and Evil',
    6 => 'The Earth, My Butt, and Other Big Round Things',
    7 => 'Cloudy With a Chance of Meatballs',
    8 => 'The Perks of Being a Wallflower',
    9 => 'Me Talk Pretty One Day',
    10 => 'One Hundred Years of Solitude',
    11 => 'A Heartbreaking Work of Staggering Genius',
    12 => 'Where the Wild Things Are',
    13 => 'How to Lose Friends and Alienate People',
    14 => 'Another Bullshit Night in Suck City',
    15 => 'The Gordonston Ladies Dog Walking Club',
    16 => 'I Am America',
    17 => 'A Clockwork Orange',
    18 => 'A Thousand Splendid Suns',
    19 => 'When You Are Engulfed in Flames',
    20 => 'Extremely Loud and Incredibly Close',
    21 => 'Neverwhere',
    22 => 'The Guernsey Literary and Potato Peel Pie Society',
    23 => 'The Grapes of Wrath',
    24 => 'I Have No Mouth and I Must Scream',
    25 => 'Their Eyes Were Watching God',
    26 => 'A Confederacy of Dunces',
    27 => 'For Whom the Bell Tolls',
);

The scenario I want here is to display 5 books per page.

I assume you already know that array indexes start with 0. So if I access page 1, the books to display are from index 0-4 which are the following:

Do Androids Dream of Electric Sheep?
The Curious Incident of the Dog in the Night-Time
The Hollow Chocolate Bunnies of the Apocalypse
To Kill a Mockingbird
The Unbearable Lightness of Being

Now let's write the pagination logic (pagination.php).

     1 <?php
     2 
     3 $page     = 1; // Show items in page 1
     4 $per_page = 5; // Number of items to show per page
     5 $num_page = 0; // Number of pages
     6 
     7 // Get page if it is set
     8 if (isset($_GET['p']) && ($_GET['p'] > 0)) {
     9     $page = (int) $_GET['p'];
    10 }
    11 
    12 $bookshelf = array('... use the sample above ...');
    13 
    14 // Calculate the data needed for our pagination
    15 $total = count($bookshelf);
    16 if ($total > $per_page) {
    17     $num_page = ceil($total / $per_page);
    18 }
    19 
    20 $offset = $per_page * ($page - 1);
    21 
    22 // Get the book titles to display in the current page
    23 $books = array_slice($bookshelf, $offset, $per_page);
    24 
    25 // Display items per page
    26 if ($books) {
    27  echo "<ul class='list-group'>";
    28  foreach ($books as $book) {
    29   echo "<li class='list-group-item'>{$book}</li>";
    30  }
    31  echo "</ul>";
    32 }
    33 
    34 // Display page buttons
    35 if ($num_page) {
    36  echo "<ul class='pagination'>";
    37  for ($i = 1; $i <= $num_page; $i++) {
    38      echo "<li><a href='?p={$i}'>{$i}</a></li>";
    39  }
    40  echo "</ul>";
    41 }


Does it look complicated? Let's break it down.

L3-5
Declares the default values

$page → the page to show if p param is absent in the url
$per_page → display 5 items per page
$num_page → number of page buttons to display

L8-10
Set $page if p param is present in the url and p is a positive int

L15-18
Set $num_page if $bookshelf contains more then 5 items. 
Otherwise, we keep it to 0 as declared in L5. 
What's the point of displaying page buttons if there's only 1 page, right?

L20
Remember the index we talked about before? 
$offset is the calculated index base from $page and $per_page values. 

We need $offset and $per_page to paginate the items in $bookshelf.

L23
We take 5 items from $bookshelf by specifying the $offset (index).

L26-32
Displays the paginated books if there are any.

L35-41
Displays the page buttons if there are any.

Now the data you need to paginate may be coming from another source, such as a database or cache.

Just construct your query like this:

$qry = "SELECT * FROM books LIMIT $offset, $per_page";

To try this pagination, download the source code.
Extract in your document root then follow this link

http://localhost/simple-pagination/index.php?p=1

To use this in your project, you may include this as a library. Just clone this repository

Well, that's all there is to creating a simple pagination. Should you find any bugs, please let me know in the comments.

Comments

  1. Hi Technews Able!
    bootstrap is just a css/html framework, just in case you don't want to style your own pagination :)
    but this snippet will actually work even in your custom css :)

    ReplyDelete
  2. Can you also let me know how to add the "next" / "previous" button code.
    Thank you.

    For the rest your code works great!

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  3. Btw, I used the https://github.com/hanapiers/t2simple-simple-pagination

    ReplyDelete
    Replies
    1. Sorry for the late reply. I only got the time now to update the library.
      I have added the Prev / Next links. You may check the github code again. https://github.com/hanapiers/t2simple-simple-pagination

      Delete

Post a Comment