How to create Pagination with PHP

Pagination helps us to split the large list of records into multiple pages.

This improves the UI and page load time.

It limits the number of records visible to the user and requires navigating through pagination control to view another list.

In this tutorial, I show how you can simple pagination with the Next and Previous button with PHP and MySQL.

How to create Pagination with PHP


Contents

  1. Table structure
  2. Configuration
  3. HTML & PHP
  4. CSS
  5. Conclusion

1. Table structure

I am using employee table in the example.

CREATE TABLE `employee` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `emp_name` varchar(100) NOT NULL,
  'salary' varchar(20) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a new config.php to define database connection.

Completed Code

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3. HTML & PHP

Create a table layout to show the employee list.

Count the total number of records in the employee table and select the specific number of records uses LIMIT with SELECT query.

NOTE – I set the maximum number of row selection to 5 ($rowperpage=5). You can change its value.

Created two hidden fields that store the current row position and the total number of records. The button elements for Previous and Next navigation.

Previous Button click –

Select the current row position and subtract it by $rowperpage.

Next Button click – 

Select the current row position and the total number of records value. Add $rowperpage with current row position if it less than $allcount.

Complete Code

<!doctype html>
<html>
    <head>
        <link href="style.css" type="text/css" rel="stylesheet">
        <?php
            include("config.php");

            $rowperpage = 5;
            $row = 0;

            // Previous Button
            if(isset($_POST['but_prev'])){
                $row = $_POST['row'];
                $row -= $rowperpage;
                if( $row < 0 ){
                    $row = 0;
                }
            }

            // Next Button
            if(isset($_POST['but_next'])){
                $row = $_POST['row'];
                $allcount = $_POST['allcount'];

                $val = $row + $rowperpage;
                if( $val < $allcount ){
                    $row = $val;
                }
            }
        ?>
    </head>
    <body>
    <div id="content">
        <table width="100%" id="emp_table" border="0">
            <tr class="tr_header">
                <th>S.no</th>
                <th>Name</th>
                <th>Salary</th>
            </tr>
            <?php
            // count total number of rows
            $sql = "SELECT COUNT(*) AS cntrows FROM employee";
            $result = mysqli_query($con,$sql);
            $fetchresult = mysqli_fetch_array($result);
            $allcount = $fetchresult['cntrows'];

            // selecting rows
            $sql = "SELECT * FROM employee  ORDER BY ID ASC limit $row,".$rowperpage;
            $result = mysqli_query($con,$sql);
            $sno = $row + 1;
            while($fetch = mysqli_fetch_array($result)){
                $name = $fetch['emp_name'];
                $salary = $fetch['salary'];
                ?>
                <tr>
                    <td align='center'><?php echo $sno; ?></td>
                    <td align='center'><?php echo $name; ?></td>
                    <td align='center'><?php echo $salary; ?></td>
                </tr>
            <?php
                $sno ++;
            }
            ?>
        </table>
        <form method="post" action="">
            <div id="div_pagination">
                <input type="hidden" name="row" value="<?php echo $row; ?>">
                <input type="hidden" name="allcount" value="<?php echo $allcount; ?>">
                <input type="submit" class="button" name="but_prev" value="Previous">
                <input type="submit" class="button" name="but_next" value="Next">
            </div>
        </form>
    </div>
    </body>
</html>

4. CSS

.container{
 border:1px solid darkgrey;
 border-radius:3px;
 padding:5px;
 width: 60%;
 margin: 0 auto;
}

/* Table */
#emp_table {
 border:3px solid lavender;
 border-radius:3px;
}

/* Table header */
.tr_header{
 background-color:dodgerblue;
}
.tr_header th{
 color:white;
 padding:10px 0px;
 letter-spacing: 1px;
}

/* Table rows and columns */
#emp_table td{
 padding:10px;
}
#emp_table tr:nth-child(even){
 background-color:lavender;
 color:black;
}

/* */
#div_pagination{
 width:100%;
 margin-top:5px;
 text-align:center;
}

.button{
 border-radius:3px;
 border:0px;
 background-color:mediumpurple;
 color:white;
 padding:10px 20px;
 letter-spacing: 1px;
}

.divnum_rows{
 display: inline-block;
 text-align: right;
 width: 30%;
}

5. Conclusion

When you have a huge number of records and want to show all on the web page then use pagination to split it into the number of pages.

To make it easier for the users to navigate you can add search control to filter the list.

You can also try the DataTables jQuery plugin for pagination. It has features like – searching, sorting, loading data with, and without AJAX.

If you found this tutorial helpful then don't forget to share.

3 thoughts on “How to create Pagination with PHP”

Leave a Comment