<< Back
Simple PHP pagination script
Simple php script that does pagination
Simple PHP pagination script
This is a simple php script which I used in a custom frame work basen on a old version of cakephp. I thought it might be good to keep as it is so simple but works so well.
In controller
// do a count query on mysql database
// example: SELECT count(*) as Count FROM users WHERE is_active = 1 GROUP BY id
// for example purposes I have simplified the queries, they might be in a model in a php frame work if you use one
    $offset = 0;
    $currentpage = $_GET['page'];
    if(!empty($currentpage)) {
      if($currentpage > 1) {
        $offset = ($currentpage - 1) * 10;
      }
    }
    $pages = $count / 10;
    $pages = ceil($pages);
    if($currentpage > 3) { $startpage = $currentpage - 3; } else {  $startpage = 1; }
    if($currentpage < ($pages - 3)) { $endpage = $currentpage + 2; } else { $endpage = $pages; }
// if you are in a framework like cakephp, laravel etc you want to pass the values to your view
// like so:
    $this->set('startpage', $startpage);
    $this->set('endpage', $endpage);
    $this->set('currentpage', $currentpage);
    $this->set('count', $count);
// query mysql insert '$offset' into the query.
// example: $query = 'SELECT * FROM users WHERE is_active = 1 GROUP BY id ORDER BY id LIMIT '.$offset.',10;
In view
<style>
  .pagination {
    display: inline-block;
    padding-left: 0;
    margin-top: 10px;
    border-radius: 4px;
    margin-bottom: 1px;
  }
  .pagination > li {
    display: inline;
  }
  .pagination > li > a, .pagination > li > span {
    position: relative;
    float: left;
    padding: 6px 12px;
    margin-left: -1px;
    line-height: 1.42857143;
    color: #428bca;
    text-decoration: none;
    background-color: #fff;
    border: 1px solid #ddd;
  }
  .pagination > .active > a {
    z-index: 2;
    color: #fff;
    cursor: default;
    background-color: #00214E;
    border-color: #00214E;
  }
</style>
<div class='pull-left'>
<?php if($count > 10){ ?>
<ul class="pagination">
<li><a href="/cwsinsurance/imagemanager/'">First</a></li>
<?php
  for ($i = $startpage; $i <= $endpage; $i++) {
    echo '<li class=';
    if( $currentpage == $i){ echo ' "active" '; }
    echo '><a href="/cwsinsurance/imagemanager/?page='.$i.'">'.$i.'</a></li>';
  }
?>
<li><a href="/cwsinsurance/imagemanager/?page=<?= $pages ?>">Last</a></li>
</ul>
<?php } ?>
</div>
 <div class='pull-right'>
Total gadgets: Â <?= $count ?>
</div>
Published: 17th March 2017 by