4

I'm searching for a "advanced" php Pagination script, that shows me 10 mysql entries per page. In the web there are many "simple" scripts (even with jQuery) like this: http://www.9lessons.info/2009/09/pagination-with-jquery-mysql-and-php.html Here is a demo: http://demos.9lessons.info/pagination.php

These simple scripts are bad when having hundreds of entries... So what I need is an advanced script - I need something like this:

When you are on Page 1 it should look like this:

[1] 2 3 4 5 ... 45

On Page 8:

1 ... 6 7 [8] 9 10 ... 45

On Page 43:

1 ... 41 42 [43] 44 45

and so on...

Many forums or blogs (e.g. wordpress) are using this technique. Can somebody please provide me with the code? There must be a "best practise code", but I can't find it. Thanks!

creativz
  • 9,039
  • 12
  • 34
  • 35
  • Questions on SO should show the code you've tried, not be just a general request for solutions. See http://stackoverflow.com/about – Blazemonger Feb 24 '14 at 15:47

4 Answers4

6

Try this out,

function generatePagination($currentPage, $totalPages, $pageLinks = 5)
{
    if ($totalPages <= 1)
    {
        return NULL;
    }

    $html = '<ul class="pagination">';

    $leeway = floor($pageLinks / 2);

    $firstPage = $currentPage - $leeway;
    $lastPage = $currentPage + $leeway;

    if ($firstPage < 1)
    {
        $lastPage += 1 - $firstPage;
        $firstPage = 1;
    }
    if ($lastPage > $totalPages)
    {
        $firstPage -= $lastPage - $totalPages;
        $lastPage = $totalPages;
    }
    if ($firstPage < 1)
    {
        $firstPage = 1;
    }

    if ($firstPage != 1)
    {
        $html .= '<li class="first"><a href="./?p=1" title="Page 1">1</a></li>';
        $html .= '<li class="page dots"><span>...</span></li>';
    }

    for ($i = $firstPage; $i <= $lastPage; $i++)
    {
        if ($i == $currentPage)
        {
            $html .= '<li class="page current"><span>' . $i . '</span></li>';
        }
        else
        {
            $html .= '<li class="page"><a href="./?p=' . $i . '" title="Page ' . $i . '">' . $i . '</a></li>';
        }
    }

    if ($lastPage != $totalPages)
    {
        $html .= '<li class="page dots"><span>...</span></li>';
        $html .= '<li class="last"><a href="./?p=' . $totalPages . '" title="Page ' . $totalPages . '">' . $totalPages . '</a></li>';
    }

    $html .= '</ul>';

    return $html;
}
Stephen Melrose
  • 4,433
  • 4
  • 26
  • 41
1

If you really have 100s of pages of results, you might want to consider paginating logarithmically.
See this post for details.

Community
  • 1
  • 1
Doin
  • 6,230
  • 3
  • 31
  • 31
0

Have a look at this plugin (jquery)

The paginator is a bit different than what you want but It will do all what you need.

Gaurav Sharma
  • 2,828
  • 1
  • 35
  • 54
0

Try this: http://pear.php.net/package/Pager

Buildstarted
  • 25,661
  • 9
  • 79
  • 93
Ashok
  • 61
  • 3