Below is the function that will generate a pagination markup as per the Bootstrap framework.
$baseUrl = 'http://abc.com/users/all'; //this will be url of the page where we need to pagination. So pagination will work by appending ?page query string to this url
//Example
//http://abc.com/users/all?page=1
//http://abc.com/users/all?page=2
$totalResults = DB::table('users')->count(); //fetch the total records. Here you may use any function specific to your framework's database model
$resultsPerPage = 10;
$currentPage = (!empty($_GET['page']) && ctype_digit($_GET['page'])) ? $_GET['page'] : 1;
$queryStringArray=[]; //read on to understand when and how to use this
echo pagination($baseUrl, $totalResults, $resultsPerPage, $currentPage, $queryStringArray);
function pagination($baseUrl, $totalResults, $resultsPerPage, $currentPage, $queryStringArray=[]) {
$totalPages = ceil($totalResults/$resultsPerPage);
if($totalPages <=1 )
return '';
$queryString = '';
if($queryStringArray)
$queryString = '&'.http_build_query($queryStringArray);
$rightLinks = $currentPage+3;
$previousLinks = $currentPage-3;
ob_start();
?>
Let's say that we have a page http://abc.com/users/all. Now instead of showing all the users on the same page we want to show only 10 users per page. So accordingly http://abc.com/users/all will show only first 10 users. Visiting http://abc.com/users/all?page=2 will show next 10 set of users and so on
To use the above pagination function we'll need below values which are parameters required by our pagination function
$baseUrl
will the url to which pagination function will append page number. For our current case it will be http://abc.com/users/all. So pagination function will append ?page=2 query string to it$totalResults
will be total number of result sets. Usually you would use count()
function to fetch it. Let's assume in our case we have 1000 users.$resultsPerPage
will be number of records in each page$currentPage
will be current page being displayed. You would check $_GET['page']
for this value$queryStringArray
Say you also want to append some search parameters to paginated links like name=Perials then you would set this to ['name'=>'Perials']
. Every paginated link will have this in query string along with the page parameter. Eg http://abc.com/users/all?page=2&name=Perialshttps://github.com/perials/pagination-function
Hi,
I implemented this code and looks perfect but at one point i am stucked which is, my additional parameters are coming from filter code. which i am storing in $url variable. I am not getting perfect result with filtered value.