Simple Pagination in PHP/MySQLi

May 31, 2020
PHP
ss

In this tutorial, I’m going to show you how to create simple pagination using PHP/MySQLi. Pagination is a set of numbers wherein each number are assigned a page or in some cases used to divide rows of MySQL table to improve visual presentation like in this tutorial.

So, let’s get started.

Creating a Database

The first step is to create our database.

1. Open phpMyAdmin.

2. Click databases, create a database and name it as “pagination”.

3. After creating a database, click the SQL and paste the below code. See image below for detailed instruction.

CREATE TABLE `user` (
  `userid` INT(11) NOT NULL AUTO_INCREMENT,
  `firstname` VARCHAR(30) NOT NULL,
  `lastname` VARCHAR(30) NOT NULL,
  `username` VARCHAR(30) NOT NULL,
PRIMARY KEY(`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

database 6 47

Inserting Sample Data into a Database

Next is to insert sample data into the database that we have created. We are going to use this in our sample table.

1. Click the “pagination” database that we have created.

2. Click SQL and paste the code below.

INSERT INTO `user` (`firstname`, `lastname`, `username`) VALUES
('neovic', 'devierte', 'nurhodelta'),
('julyn', 'divinagracia', 'julyn'),
('lee', 'ann', 'lee09'),
('tintin', 'demapanag', 'tin45'),
('dee', 'tolentino', 'deedee'),
('jaira', 'jacinto', 'jjacinto'),
('tetai', 'devi', 'tdevi'),
('tintin', 'hermosa', 'tinhermosa'),
('piolo', 'pascual', 'ppascual'),
('lee', 'bagun', 'faker'),
('barny', 'dino', 'bdino');

Creating a Connection

Next step is to create a database connection and save it as “conn.php”. This file will serve as our bridge between our form and our database. To create the file, open your HTML code editor and paste the code below after the tag.

<?php
 
//MySQLi Procedural
$conn = mysqli_connect("localhost","root","","pagination");
if (!$conn) {
 die("Connection failed: " . mysqli_connect_error());
}
 
?>

Creating a Pagination Code

Next step is to create our pagination. We name this as “pagination.php”.

<?php
 
    include("conn.php");
 
    $query=mysqli_query($conn,"select count(userid) from `user`");
    $row = mysqli_fetch_row($query);
 
    $rows = $row[0];
 
    $page_rows = 10;
 
    $last = ceil($rows/$page_rows);
 
    if($last < 1){
        $last = 1;
    }
 
    $pagenum = 1;
 
    if(isset($_GET['pn'])){
        $pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
    }
 
    if ($pagenum < 1) { 
        $pagenum = 1; 
    } 
    else if ($pagenum > $last) { 
        $pagenum = $last; 
    }
 
    $limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
 
    $nquery=mysqli_query($conn,"select * from `user` $limit");
 
    $paginationCtrls = '';
 
    if($last != 1){
 
    if ($pagenum > 1) {
        $previous = $pagenum - 1;
        $paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$previous.'" class="btn btn-default">Previous</a> &nbsp; &nbsp; ';
 
        for($i = $pagenum-4; $i < $pagenum; $i++){
            if($i > 0){
                $paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'" class="btn btn-default">'.$i.'</a> &nbsp; ';
            }
        }
    }
 
    $paginationCtrls .= ''.$pagenum.' &nbsp; ';
 
    for($i = $pagenum+1; $i <= $last; $i++){
        $paginationCtrls .= '<a href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'" class="btn btn-default">'.$i.'</a> &nbsp; ';
        if($i >= $pagenum+4){
            break;
        }
    }
 
    if ($pagenum != $last) {
        $next = $pagenum + 1;
        $paginationCtrls .= ' &nbsp; &nbsp; <a href="'.$_SERVER['PHP_SELF'].'?pn='.$next.'" class="btn btn-default">Next</a> ';
    }
    }
 
?>

Creating a Sample Table

Lastly, we create our sample table. We name this as our “index.php”.

<?php include('pagination.php'); ?>
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div style="height: 20px;"></div>
    <div class="row">
    <div class="col-lg-2">
    </div>
    <div class="col-lg-8">
    <table width="80%" class="table table-striped table-bordered table-hover">
        <thead>
            <th>UserID</th>
            <th>Firstname</th>
            <th>Lastname</th>
            <th>Username</th>
        </thead>
        <tbody>
        <?php
            while($crow = mysqli_fetch_array($nquery)){
            ?>
                <tr>
                    <td><?php echo $crow['userid']; ?></td>
                    <td><?php echo $crow['firstname']; ?></td>
                    <td><?php echo $crow['lastname']; ?></td>
                    <td><?php echo $crow['username']; ?></td>
                </tr>
            <?php
            }		
        ?>
        </tbody>
    </table>
    <div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
    </div>
    <div class="col-lg-2">
    </div>
    </div>
</div>
</body>
</html>

That’s it. In case you’re having trouble with the database, I have included sample database in the file of this tutorial located in ‘db’ folder. If you have any comments or questions, feel free to comment below or message me here in sourcecodester.com via private message.

Download Here
Comments
  • How to use this code to work with variable comes from previous page with link $_POST:
    http://link?=user_id

    Bernard September 29, 2021 5:26 am Reply

Leave a Reply

Your email address will not be published. Required fields are marked *