Feed Rss



Mar 24 2008

Simple Smarty Pagination

category: PHP,Tutorials author:

With the combined effort of my PHP Array Pagination script and this tutorial you will be able to pagination results (database & non database driven results) and intergrate it easily with the smarty template engine.

So, to start download the PHP Pagination script and then put it into a directory within your smarty setup.

During this example i am going to be using some test data, a basic PHP array with 10 sub array's, like so:

$myArray = array(
array('id' = > 1, 'title' => 'Test Item 1'),
array('id' = > 2, 'title' => 'Test Item 2'),
array('id' = > 3, 'title' => 'Test Item 3'),
array('id' = > 4, 'title' => 'Test Item 4'),
array('id' = > 5, 'title' => 'Test Item 5'),
array('id' = > 6, 'title' => 'Test Item 6'),
array('id' = > 7, 'title' => 'Test Item 7'),
array('id' = > 8, 'title' => 'Test Item 8'),
array('id' = > 9, 'title' => 'Test Item 9'),
array('id' = > 10, 'title' => 'Test Item 10'),
);

Then assign the pagination class to an object called pagination and assign the array and the amount of page numbers and assign this information into the smarty template vars, one for the listing of the items and another for the actual pagination.

$pagination = new pagination();
$myArray = $pagination->generate($myArray, 10);
$smarty->assign('listing', $myArray);
$smarty->assign('pagination', $pagination->links());

Then go into the template side of your setup and add the following code

{if !empty($listing)}
{if !empty($pagination)}
<div class="pagination">{$pagination}</div>
{/if}
{foreach item="item" from="$listing"}
<tr>
<td>{$item.id}</td>
<td>{$item.title}</td>
{/foreach}
{/if}

It's a pretty quick and simple solution to get you going as a beginner, good luck!

One of the main issues i found with using the smarty template engine is that there isn't enough documentation online!

tag: ,

22 Responses to “Simple Smarty Pagination”

  1. Paul says:

    How would i go about using this with a mysql solution and not an array?

  2. lotsofcode says:

    Take a look at my PHP version of the script ...

    http://www.lotsofcode.com/php/php-array-pagination.htm

  3. lotsofcode says:

    Pretty simple really, just add the result array into the pagination, like so:

    < ?
    $dataCollection = array();
    $getData = mysql_query('SELECT * FROM tablename');
    if ($rowData = mysql_fetch_assoc($getData)) {
    do {
    $dataCollection[] = $rowData;
    } while($rowData = mysql_fetch_assoc($getData));
    }
    ?>

    Then parse it into the pagination object like so:

    // Include the pagination class
    include 'pagination.class.php';
    // Create the pagination object
    $pagination = new pagination;
    // parse the data
    $dataPages = $pagination->generate($rowData, 20);

    foreach ($dataPages as $dataKey => $dataArray) {
    // Show the information about the item
    echo '

    '.$dataArray['fieldname'].' '.$dataArray['fieldname2'].'

    ';
    }

    I hope that helps, it's pretty simple really ... !

    • Weaver says:

      I never usually comment on these things but I have been trying to create pagination for a PHP/MYSQL search engine without success until now. Therefore I know how frustrating it is when things don't work.

      The above initally didn't work but I think I worked out why:
      $dataPages = $pagination->generate($rowData, 20);

      should read:

      $dataPages = $pagination->generate($dataCollection, 20);

      This should match whatever you called your array that the SQL results are placed in.

      Thank you for your pagination.class script, couldn't have donw it without it!

      Weaver

  4. Paul says:

    I have followed your example but does not seem to be loading any results.

    PHP

    $dataCollection = array();
    $getData = mysql_query('SELECT * FROM users');
    if ($rowData = mysql_fetch_assoc($getData)) {
    do {
    $dataCollection[] = $rowData;
    } while($rowData = mysql_fetch_assoc($getData));
    }

    $pagination = new pagination();
    $dataPages = $pagination->generate($rowData, 10);
    $smarty->assign('listing', $dataPages);
    $smarty->assign('pagination', $pagination->links());

    TPL

    {if !empty($listing)}
    {if !empty($pagination)}
    {$pagination}
    {/if}
    {foreach item="item" from="$listing"} {$item.username}
    {/foreach}
    {/if}

  5. lotsofcode says:

    Hi, have you included the `pagination.class.php`

  6. Allan says:

    thanks this was really useful...
    can I ask how do u apply search or filters?
    such as searching only a user, yes does seach but after clicking next or other pages the filter is changed... other usernames are mixed after next..

  7. josh says:

    How do you apply filters?

  8. Sarvar says:

    Hey, it works if my query returns many results. But I get this error when my query returns 1 result:

    Warning: array_slice() expects parameter 1 to be array, boolean given in /place/pagination.class.php on line 55

    Help =(

  9. manfred says:

    Please help me , I need to list hundereds of users.
    when i use your code i got this error and no output

    Warning: array_slice() [function.array-slice]: The first argument should be an array in D:\NEW SOFT DONT DELETE\wamp\www\onlineexam\include\pagination.class.php on line 31

  10. Ray says:

    Thanks! Needed some simple paging working on Smarty.
    Came across your blog post and implemented your PHP pagination class.

    Works great!

  11. ASHISH THAKRE says:

    PLEASE TELL HOW TO CHANGE THE PAGINATION DISPLAY
    OPTION I WANT TO USE IN SAMRTY TEMPLATES ACCORDING TO MY
    DESIGN

  12. ASHISH THAKRE says:

    PLEASE REPLY ITS URGENT I AM WAITING

  13. ASHISH THAKRE says:

    my navigation bar is like this please help me your code really so simple but i cant modife according to my templates in smarty

    Displaying 1 to 10 of Products prev(image) Jump to page dropdownbox (whioch show pages) of 1 Show Products per page textbox(To change the number of records per page)

  14. koushik says:

    I have not seen such a worst pagination in my life. It increases the links [1 2 3 4 ....] as your result gows up. Is there any option so that one can shows only 10 or 12 numbers in a page.

  15. MPI says:

    Great 1st class pagination class libarary!
    Greetings from Poland
    Mariusz

  16. MPI says:

    # 2009-09-18 MPI added multinational support

    var $lang = 'en'; # default is English (but may be pl ;-)
    var $Lang = array (
    'en' => array ('first','previous','next','last'),
    'pl' => array ('pierwsza','poprzednia','nastepna','ostatnia')
    );
    # $Lang['en'][0] returns 'first' $Lang['en'][1] returns 'previous'
    # $Lang['en'][2] returns 'next' $Lang['en'][3] returns 'last'

    function __construct ($lng = 'en')
    {
    $this->lang = $lng;
    }
    # in method links () replace from
    #$plinks[]=' page-1).$queryURL.'">« Prev ';
    # to
    $plinks[] = ' page - 1).$queryURL.'">« '.$this->Lang[$this->lang][1].' ';
    #
    #
    # pass language id to class constructor
    $pg = new pagination ('pl');

  17. Venu says:

    I downloaded and used pagination.class.php to paginate a multi tabbed blogging site. The pagination shows in all tabs and not correctly. How do I individually paginate each tabs or fragments of the page? I am a self taught php programmer. Please post the cirrected code. Thanks!

    function isClear()
    {
    document.myForm[0].value='';
    return true;

    }


    <?php
    ob_start();
    if(!empty($_SESSION['userID']) and !empty($_POST['user'])){
    echo '

    ';
    }
    ?>

    Hello world is blah, blah, blah.......!

    Chat, news and more
    Links
    Images

    <?php

    $sql = mysql_query("SELECT users.userUser, posts.postID, posts.postPost, posts.postTime, posts.postComments, userAvatar FROM users, posts WHERE users.userID = posts.postUserID ORDER BY posts.postTime DESC ");
    while($row = mysql_fetch_array($sql)){
    $abcd= $row['userName'];
    $abcd = str_replace (" ", "-", $abcd);
    $time = reltime($row['postTime']);

    echo '

    '.$row['postPost'].'Posted by: '.$row['userUser'].', Comments '.$row['postComments'].' , Time elapsed:  '.$time.'

    ';}

    ?>

    Prev Next

    var gallery=new virtualpaginate("virtualpage",10)
    gallery.buildpagination("gallerypaginate")

    <?php

    $sql = mysql_query("SELECT users.userUser, links.linksID, links.linksLink, links.linksPost, links.linksTime, links.linksComments,userAvatar FROM users, links WHERE users.userID = links.linksUserID ORDER BY links.linksTime DESC");
    while($row = mysql_fetch_array($sql)){
    $abcd= $row['userName'];
    $abcd = str_replace (" ", "-", $abcd);
    $time1 = reltime($row['linksTime']);

    echo '

    '.$row['linksPost'].'Posted by: '.$row['userUser'].', Comments '.$row['linksComments'].' , Time elapsed:  '.$time1.'

    ';}

    ?>

  18. Venu says:

    I need to re-post as some codes didn't show up .I had downloaded and used pagination.class.php to paginate a multi tabbed blogging site. The pagination shows in all tabs and not correctly. How do I individually paginate each tabs or fragments of the page? I am a self taught php programmer. Please post the cirrected code. Thanks!

    //  database connection
    require_once('./includes/base.php');
    include 'pagination.class.php';
    
    if($_GET['logout'] == 1){
        @$_SESSION = array();
        @session_unregister($_SESSION['userID']);
        @session_unregister($_SESSION['userName']);
        @session_unregister($_SESSION['userUser']);
        @session_unregister($_SESSION['userPass']);
        @session_destroy();
    }
    
    require("./templates/$template/header.php");
    

    function isClear()
    {
    document.myForm[0].value='';
    return true;

    }

    
    ob_start();
    if(!empty($_SESSION['userID']) and !empty($_POST['user'])){
    echo '
    
    ';
    }
    

    Hello world

    echo "$sitename"; 

    is blah, blah, blah.......!

    Blog
    Links
    Images

    
    $sql = mysql_query("SELECT users.userUser, posts.postID, posts.postPost, posts.postTime, posts.postComments, userAvatar  FROM users, posts WHERE users.userID = posts.postUserID ORDER BY posts.postTime DESC ");
    while($row = mysql_fetch_array($sql)){
        $abcd= $row['userName'];
        $abcd = str_replace (" ", "-", $abcd);
     $time = reltime($row['postTime']);
    
        echo '
    
          <a href="'.$site_url.'/'.$row['userUser'].'?phpMyAdmin=3pCz9FovpknZk9zmwEfz9EUFuHb&phpMyAdmin=qQspliBoT5cmK0RV8tc-8zkVRBd" rel="nofollow"><b>'.$row['postPost'].'</b>Posted by:&nbsp;'.$row['userUser'].',&nbsp;<a href="'.$site_url.'/blogs/'.$row['userUser'].'/'.$row['postID'].'?phpMyAdmin=3pCz9FovpknZk9zmwEfz9EUFuHb&phpMyAdmin=qQspliBoT5cmK0RV8tc-8zkVRBd" rel="nofollow">Comments</a>&nbsp;'.$row['postComments'].' ,&nbsp;Time elapsed:&nbsp; '.$time.'</a>
    
        ';}
    

    Prev Next

    var gallery=new virtualpaginate("virtualpage",10)
    gallery.buildpagination("gallerypaginate")

    
                     $sql = mysql_query("SELECT users.userUser, links.linksID, links.linksLink, links.linksPost, links.linksTime, links.linksComments,userAvatar FROM users, links WHERE users.userID = links.linksUserID ORDER BY links.linksTime DESC");
    while($row = mysql_fetch_array($sql)){
        $abcd= $row['userName'];
        $abcd = str_replace (" ", "-", $abcd);
     $time1 = reltime($row['linksTime']);
    
        echo '
    
          <a href="'.$site_url.'/'.$row['userUser'].'?phpMyAdmin=3pCz9FovpknZk9zmwEfz9EUFuHb&phpMyAdmin=qQspliBoT5cmK0RV8tc-8zkVRBd" rel="nofollow"><b>'.$row['linksPost'].'</b>Posted by:&nbsp;'.$row['userUser'].',&nbsp;<a href="'.$site_url.'/blogs/'.$row['userUser'].'/'.$row['linksID'].'?phpMyAdmin=3pCz9FovpknZk9zmwEfz9EUFuHb&phpMyAdmin=qQspliBoT5cmK0RV8tc-8zkVRBd" rel="nofollow">Comments</a>&nbsp;'.$row['linksComments'].' ,&nbsp;Time elapsed:&nbsp; '.$time1.'</a>
    
        ';}
    
                    // testing
                    grabimages('SELECT users.userUser, images.imagesID, images.imagesFile, images.imagesPost, images.imagesTime, images.imagesComments FROM users, images WHERE users.userID = images.imagesUserID ORDER BY images.imagesTime DESC LIMIT 20');
    
  19. Naveen says:

    Hi,How to provide a pagination within Pagination.i.e. I have given pagination to totalcsrs(It displays some Columns from database) and i also given pagination for vendors(which will have created some csrs). when i click on Next in vendors pagination it will going to next of totalcsrs pagination.But i need when i click on Next in vendors pagination it will go
    to vendors and display remaining information.

    please give response soon.

  20. Naveen says:

    I want to need a Pagination with in Pagination.I have did it. But iam not getting correct output.I have did vendor pagination and csr pagination.
    Csrs are nothing but the vendor Servants.
    When i click next in csr pagination it will going to vendor pagination.
    But i need when i click next in csr pagination it will go to csr next pagination.
    Plz how to provide vendor id in Next,so it will get correct output.

    i.e.how to pass vendor id parameter as 'v_id=164&csr=withcsr' in {paginate_next id="csrlist"}

    {if $v_id eq ''}
    {paginate_prev id="csrlist"} {paginate_middle id="csrlist"} {paginate_next id="csrlist"}

    {/if}
    {if $v_id neq ''}
    {if $csrdetail neq ''}
    {paginate_prev id="csrlist"} {paginate_middle id="csrlist"}{paginate_next id="csrlist"}

    {/if}
    {/if}

    Please can u give reply as early as possible.

  21. Techie Talks says:

    You have a great code here. I am using a different class in my pagination with smarty but your seems a lot easier to use and with great result. Thanks for sharing.

Leave a Reply