How to make pagination in php mysql

By Ved Prakash N | Sep 24, 2023 | PHP
Share : Whatsapp

How to Create Pagination in PHP and MYSQL

In this post, we will be learning about how to make dynamic pagination in php mysql. This code is very simple to learn and integrate into the project. In this pagination we show 10 records per page (paginate), if you want to change the per page paginate value in the code.


The below code is for creating dynamic pagination in php mysql where we show 10 record per page (paginate):

    $conn = mysqli_connect('localhost','root','','fundacodester');
        die('Connection Failed'. mysqli_connect_error());
<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to make pagination in php mysql</title>
    <link href="" rel="stylesheet" >

    <div class="container">
        <div class="row">
            <div class="col-md-12">

                <div class="text-center my-4">
                    <h1>How to make pagination in php mysql</h1>

                    $countryQuery = mysqli_query($conn, "SELECT * FROM countries");
                    $totalCountry = mysqli_num_rows($countryQuery); //counting total number of rows

                    if(!isset ($_GET['page'])){
                        $page_number = 1;
                            $page_number = 1;
                            $page_number = $_GET['page'];
                    $limitPerPage = 10;

                    $startFrom = ($page_number-1) * $limitPerPage;

                    $countries = mysqli_query($conn, "SELECT * FROM countries LIMIT " . $startFrom . ',' . $limitPerPage);
                    $total_pages = ceil($totalCountry / $limitPerPage);


                <table class="table table-bordered table-striped">
                        <?php foreach($countries as $country) : ?>
                                <td><?= $country['id']; ?></td>
                                <td><?= $country['country']; ?></td>
                        <?php endforeach; ?>

                <div class="float-end">
                    <nav aria-label="Page navigation example">
                        <ul class="pagination">
                            <?php for($pagination = 1; $pagination <= $total_pages; $pagination++) : ?>
                                <li class="page-item
                                    <?= isset($_GET['page']) ? ($_GET['page'] == $pagination ? 'active':'') : ($pagination == 1 ? 'active':''); ?>
                                    <a class="page-link" href="index.php?page=<?= $pagination; ?>">
                                        <?= $pagination; ?>
                            <?php endfor; ?>

    <script src=""></script>


I hope this helps you.