Skip to content

Instantly share code, notes, and snippets.

@marifuli
Created August 27, 2021 17:32
Show Gist options
  • Save marifuli/883e278430b2478c92870f3fad8861b2 to your computer and use it in GitHub Desktop.
Save marifuli/883e278430b2478c92870f3fad8861b2 to your computer and use it in GitHub Desktop.
Raw PHP-MySQL Pagination
<?php
// php >= 7.0
function paginate ($total, $per_page, $curr_page)
{
$url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$result = [];
$result['html'] = '<div class="pagination">';
$result['offset'] = ($curr_page - 1) < 0 ? 0 : ($curr_page - 1) * $per_page ;
$numOfPage = ceil($total / $per_page);
if($numOfPage > 1)
{
if($numOfPage < 7 )
{
for($i = 1; $i <= $numOfPage; $i++ )
{
if($i == $curr_page)
$result['html'] .= '<a class="active">'.$i.'</a>';
else
$result['html'] .= '<a href="'.changeValOfUrl('page', $i).'">'.$i.'</a>';
}
}
else
{
//- if the page is in middle
if(($curr_page-3) >= 1 && ($curr_page+3) <= $numOfPage)
{
$from = $curr_page - 3;
$to = $curr_page + 3;
for ($i=$from; $i <= $to ; $i++) {
if($i == $curr_page)
$result['html'] .= '<a class="active">'.$i.'</a>';
else
$result['html'] .= '<a href="'.changeValOfUrl('page', $i).'">'.$i.'</a>';
}
}
//- if the page is close to last page
else if(($curr_page-3) >= 1 && ($curr_page+3) >= $numOfPage)
{
$from = $curr_page - 3;
$to = ($curr_page + 3) > $numOfPage ? $numOfPage : ($curr_page + 3);
for ($i=$from; $i <= $to ; $i++) {
if($i == $curr_page)
$result['html'] .= '<a class="active">'.$i.'</a>';
else
$result['html'] .= '<a href="'.changeValOfUrl('page', $i).'">'.$i.'</a>';
}
}
//- if the page is close to first page
else if(($curr_page-3) < 1 && ($curr_page+3) <= $numOfPage)
{
$from = ($curr_page - 3) < 1 ? 1 : ($curr_page - 3);
$to = $curr_page + 3;
for ($i=$from; $i <= $to ; $i++) {
if($i == $curr_page)
$result['html'] .= '<a class="active">'.$i.'</a>';
else
$result['html'] .= '<a href="'.changeValOfUrl('page', $i).'">'.$i.'</a>';
}
}
}
}
$from = ($total == 0) ? 0 : ($result['offset'] + 1);
$result['html'] .= '</div>';
$result['html'] .= 'Showing '.$from.' to '. (($result['offset']+$per_page) < $total ? ($result['offset']+$per_page) : $total ).' of '. $total;
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment