How to load more data from database using PHP

When you have lots of records on your webpage and if you want to load these records in some segment or in some limited bunch like at a time five records will display while click on load more button. We will create live demo example or steps to load more data from database using PHP.

Load more with PHP

Let as see step by steps to configure Load more data option in your webpage.

Step 1: Create one file index.php

In this file first we will include jQuery libraries with some custom css as below:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<style type="text/css">
    .loader-div {
        display: none;
        position: fixed;
        margin: 0px;
        padding: 0px;
        right: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        background-color: #fff;
        z-index: 30001;
        opacity: 0.8;
    }
    .loader-img {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
    }
</style>

Step 2: Write HTML code where you can display your dynamic data and Load more button.

<body>
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Event #</th>
                            <th>Event name</th>
                            <th>Start date</th>
                            <th>End date</th>
                        </tr>
                    </thead>
                    <tbody id="dynamic_data">
                    </tbody>
                </table>
                <center>
<button type="button" class="btn btn-success" onclick="display_data()">Load more</button>
</center>
                <input type="hidden" id="rowcount" name="rowcount" value="0">
            </div><!-- end col -->
            </form>
        </div><!--  end row -->
    </div>
    <br>
    <center>Developed by <a href="https://shinerweb.com/">Shinerweb</a></center>
    <div class="loader-div">
        <img class="loader-img" src="ajax-loader.gif" style="height: 120px;width: auto;" />
    </div>
</body>

Load more data from database

In above code firstly we have design one simple table and here you can see we take one ID as id=”dynamic_data” and that id we will use to display our dynamic data which is coming from the database.

Also we have take one button and pass one method like onclick=”display_data()”. By using this method you can call one AJAX to get data from the database.

We take one hidden field with id=”rowcount” to store our last row count of your records.

Step 3: Create AJAX call to get data from the database.

<script type="text/javascript">
    display_data();
    function display_data() {
        var rowcount = $("#rowcount").val();
        $(".loader-div").show(); // show loader
        $.ajax({
            url: "display_data.php",
            type: "POST",
            data: {
                rowcount: rowcount
            },
            dataType: 'json',
            success: function(response) {
                if (response.status == true) {
                    $("#rowcount").val(response.rowcount);
                    $('#dynamic_data').append(response.data);
                    $(".loader-div").hide(); // hide loader
                } else {
                    $(".loader-div").hide(); // hide loader
                    alert(response.msg);
                }
            },
            error: function(xhr, status) {
                $(".loader-div").hide(); // hide loader	
                console.log('ajax error = ' + xhr.statusText);
                alert(response.msg);
            }
        });
    }
</script>

Above code you must have to write inside <script> tag and here you can see we created one function display_data() and by using this function we will get the data from the database.

In this ajax block we call one file display_data.php with some parameter like rowcount and get the data from the database in small bunch or in a small segment.

Step 4: Fetch data from the database.

Create one PHP file like display_data.php and write one select query to get data from the table.

<?php
require "database_connection.php";
$last_rowcount = $_POST["rowcount"];
$rowcount = $_POST["rowcount"] + 5; //set next row count for load more data
$display_query = "select event_id,event_name,event_start_date,event_end_date from calendar_event_master order by event_id asc limit $last_rowcount,5";
$results = mysqli_query($con, $display_query);
$count = mysqli_num_rows($results);
if ($count > 0) {
    $dynamic_data = "";
    while ($data_row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
        $dynamic_data .=
            "<tr><td>" .
            $data_row["event_id"] .
            "</td><td>" .
            $data_row["event_name"] .
            "</td><td>" .
            $data_row["event_start_date"] .
            "</td><td>" .
            $data_row["event_end_date"] .
            "</td></tr>";
    }
    $data = [
        "status" => true,
        "rowcount" => $rowcount,
        "msg" => "Successfully!",
        "data" => $dynamic_data,
    ];
} else {
    $data = [
        "status" => false,
        "msg" => "Error!",
    ];
}
echo json_encode($data);
?>

In above code first we need to include our database connection file database_connection.php.

<?php
$hostname = "localhost";
$username = "your_user";
$password = "your_password";  
$database = "your_database";   
$con=mysqli_connect($hostname,$username,$password,$database);    
?> 

Now you need to get data from the table so for that we have created below sample table with some dummy data.

CREATE TABLE `calendar_event_master` (
  `event_id` int(11) NOT NULL AUTO_INCREMENT,
  `event_name` varchar(255) DEFAULT NULL,
  `event_start_date` date DEFAULT NULL,
  `event_end_date` date DEFAULT NULL,
  PRIMARY KEY (`event_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

insert into `calendar_event_master`(`event_id`,`event_name`,`event_start_date`,`event_end_date`) values (1,'Test Event1','2022-10-01','2022-10-02');
insert into `calendar_event_master`(`event_id`,`event_name`,`event_start_date`,`event_end_date`) values (2,'Test Event2','2022-10-13','2022-10-20');
insert into `calendar_event_master`(`event_id`,`event_name`,`event_start_date`,`event_end_date`) values (3,'Test Event3','2022-10-16','2022-10-27');
insert into `calendar_event_master`(`event_id`,`event_name`,`event_start_date`,`event_end_date`) values (4,'Test Event1','2022-10-01','2022-10-02');
insert into `calendar_event_master`(`event_id`,`event_name`,`event_start_date`,`event_end_date`) values (5,'Test Event2','2022-10-13','2022-10-20');
insert into `calendar_event_master`(`event_id`,`event_name`,`event_start_date`,`event_end_date`) values (6,'Test Event3','2022-10-16','2022-10-27');
insert into `calendar_event_master`(`event_id`,`event_name`,`event_start_date`,`event_end_date`) values (7,'Test Event3','2022-10-16','2022-10-27');

Execute above SQL on your database and after that you can write your PHP code to get data from the table and after that send those records as a response by using json_encode() method.

Related Posts

Divyesh Patel

I'm Divyesh Patel, Web & App developer. I want to make things that make a difference. With every line of code, i strive to make the web a beautiful place.

Leave a Reply