Skip to content

Instantly share code, notes, and snippets.

@alexsasharegan
Last active August 18, 2016 19:30
Show Gist options
  • Save alexsasharegan/03b04207c12d20a9fa68d9ce8dba612e to your computer and use it in GitHub Desktop.
Save alexsasharegan/03b04207c12d20a9fa68d9ce8dba612e to your computer and use it in GitHub Desktop.
Calculates pages using mySQL offset/limit and renders html for a predefined amount of pages
<?php
$limit = 25;
$pageDisplayLimit = 10 - 1;
$currentPage = $offset / $limit + 1;
$totalPages = ceil($count / $limit);
$pagesRemaining = $totalPages - $currentPage;
$lastPageToDisplay = $currentPage + $pageDisplayLimit <= $totalPages
? $currentPage + $pageDisplayLimit
: $totalPages;
$nextPageExists = $lastPageToDisplay < $totalPages;
if ($lastPageToDisplay === $totalPages) {
$pageIndex = $totalPages - $pageDisplayLimit > 0
? $totalPages - $pageDisplayLimit
: 1;
$backBtnIndex = $pageIndex - ($pageDisplayLimit + 1) > 0
? $pageIndex - ($pageDisplayLimit + 1)
: 1;
$prevOffset = $backBtnIndex * $limit - $limit;
$prevPageExists = $pageIndex > 1;
} else {
$pageIndex = $currentPage;
$backBtnIndex = $currentPage - ($pageDisplayLimit + 1) > 0
? $currentPage - ($pageDisplayLimit + 1)
: 1;
$prevOffset = $backBtnIndex * $limit - $limit;
$prevPageExists = $currentPage > 1;
}
if ($prevPageExists) {
$backBtn = <<<EOT
<li><a href="#">&laquo;</a></li>
EOT;
echo $backBtn;
}
for (; $pageIndex <= $lastPageToDisplay; $pageIndex++) {
$pageOffset = ($limit * $pageIndex) - $limit;
$activePage = $pageIndex == $currentPage ? 'class="active-page"' : '';
echo <<<EOT
<li><a $activePage href="#">$pageIndex</a></li>
EOT;
}
if ($nextPageExists) {
$thisOffset = $lastPageToDisplay * $limit;
$nextBtn = <<<EOT
<li><a href="#">&raquo;</a></li>
EOT;
echo $nextBtn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment