Thursday, May 17, 2012

Simple Paging

Paging literally means making data displayed in multiple pages. Paging is used specially for website, where displaying large amount of data can be so troublesome by making the downloaded data bigger and thus increasing the response time.

Paging can be done in many ways. In this tutorial, I would like to show you a very simple method we can use to do the paging. Here, we just need to enable the user to move to the next page (if any) and back to the previous page (if any). Also, for the sake of simplicity, I will use dummy data stored hard-codedly into an array. However, the concept is similar. OK, let's start !!!

    /* Maximum number of items to show, per page */
    $maxItemPerPage = 10 ;
    
    /* 
     * Prepare the dummy data
     * Used just for the sake of this tutorial.
     */
    $data = array ( ) ;

    for ( $i = 1 ; $i <= 112 ; $i ++ )
        array_push( $data , "Item " . $i ) ;
First of all, we define the maximum number of items to show per page. In this tutorial, I set the maximum number of items to show per page to 10 items. This value can be changed according to your need. However, sometimes, this value can also be changed by users as to accommodate his preferences. Sometimes, users' screen is big enough to show large count of data per page. After that, I created dummy data. Please not that in reality, mostly data stored in the database.

    /* 
     * Create function to retrieve the data.
     * 
     * The content of this function must be changed
     * according to the neccessity and logic of your
     * application regarding the data retrieval process.
     */
    function retrieveData ( $pageNumber )
    {
        global $data ;
        global $maxItemPerPage ;
        
        /* page the data */
        /* Prepares the variable used to store paged data */
        $result = array ( ) ;
        
        /* Calculate the data count */
        $dataCount = count ( $data ) ;
        
        /* Calculate the offset. Offset literally means from what index should we start retrieving the data */
        $offset = ( $pageNumber - 1 ) * $maxItemPerPage ;
        
        /* Calculate the maximum index we can use to retrieve the data */
        $limit = $offset + $maxItemPerPage ;
        
        /* Check if the limit is more than the number of data we have, just set the limit to the data count */
        if ( $limit > $dataCount )
            $limit = $dataCount ;
        
        /* Store the data now */
        for ( $i = $offset ; $i < $limit ; $i ++ )
            array_push ( $result , $data [ $i ] ) ;
        
        /* Return the paging result */
        return $result ;
    }
The next step, I created a helper function to ease the retrieval of data. All the retrieval data logic put into that function. Also note that the content of that function must be changed according to the way you retrieve the data. If you use SQL to retrieve the data, you can use the SQL Query to do the paging automatically. Here, I will show you an example of how to filter data retrieved using MySQL SQL command. Please refer to your DBMS documentation for command supported in your own DBMS.
SELECT <columns> FROM <table> LIMIT <limit>, <offset>

    /* Get the page number from query string */
    $page = $_GET [ "p" ] ;
    
    /* If not "p" (page) given, then assume the requested is page 1 */
    if ( ! isset ( $page ) )
        $page = 1 ;
    
    /* Calculate max page number */
    $maxPageNumber = ceil ( count ( $data ) / $maxItemPerPage ) ;    
    $paged_data = retrieveData ( $page ) ;
One part we need to handle is to get the requested page number sent by the user. We can easily pass it using query string passed into the server. Note that, for security sake, you should always check for the validity of values passed by the user, in case they want to inject something bad into your server by using the weakness or security hole you created unintentionally by your bad code. For this tutorial, I omit that checking.

As you can see, I use "p" variable that is sent to server using HTTP GET method to store the requested page number. If, the "p" variable is empty, I assume that the user is requesting data in the first page. So, all required data is ready, I now just need to display the data to the user.
    /* Print the data */
    echo "<table style=\"width: 100%\" border=\"1\"><tr><th style=\"background-color: #00FFAA\">Items</th></tr>" ;
    
    /* Loop through the paged-data */
    foreach ( $paged_data as $item )
        echo "<tr><td style=\"background-color: #EEEEEE\">$item</td></tr>" ;
    
    /* Print the prev/next page link */
    if ( $maxPageNumber > 1 )
    {
        echo "<tr><td style=\"background-color: #00FFFF; text-align: center\">" ;
        
        /* We can go backward to previous page since the minimum page is 1 and we are currently not at page 1 */
        if ( $page > 1 )
            echo "<a href=?p=" . ( $page - 1 ) . ">Prev. Page</a>  " ;
        
        /* We can go forward to the next page since the current page is still less than the maximum page */
        if ( $page < $maxPageNumber )
            echo "<a href=?p=" . ( $page + 1 ) . ">Next Page</a>" ;
        
        echo "</td></tr>" ;
    }
        
    echo "</table>" ;
?>
I think the printing process is very common. I don't really need to explain it a bit deeper, I suppose. The logic you need to have a look is actually the checking whether we need to display the "Prev. Page" link and "Next Page" link or not. The inline documentation should explain better. See below for the full source code.
<?php
    /* Maximum number of items to show, per page */
    $maxItemPerPage = 10 ;
    
    /* 
     * Prepare the dummy data
     * Used just for the sake of this tutorial.
     */
    $data = array ( ) ;

    for ( $i = 1 ; $i <= 112 ; $i ++ )
        array_push( $data , "Item " . $i ) ;
    
    /* 
     * Create function to retrieve the data.
     * 
     * The content of this function must be changed
     * according to the neccessity and logic of your
     * application regarding the data retrieval process.
     */
    function retrieveData ( $pageNumber )
    {
        global $data ;
        global $maxItemPerPage ;
        
        /* page the data */
        /* Prepares the variable used to store paged data */
        $result = array ( ) ;
        
        /* Calculate the data count */
        $dataCount = count ( $data ) ;
        
        /* Calculate the offset. Offset literally means from what index should we start retrieving the data */
        $offset = ( $pageNumber - 1 ) * $maxItemPerPage ;
        
        /* Calculate the maximum index we can use to retrieve the data */
        $limit = $offset + $maxItemPerPage ;
        
        /* Check if the limit is more than the number of data we have, just set the limit to the data count */
        if ( $limit > $dataCount )
            $limit = $dataCount ;
        
        /* Store the data now */
        for ( $i = $offset ; $i < $limit ; $i ++ )
            array_push ( $result , $data [ $i ] ) ;
        
        /* Return the paging result */
        return $result ;
    }
        
    /* Get the page number from query string */
    $page = $_GET [ "p" ] ;
    
    /* If not "p" (page) given, then assume the requested is page 1 */
    if ( ! isset ( $page ) )
        $page = 1 ;
    
    /* Calculate max page number */
    $maxPageNumber = ceil ( count ( $data ) / $maxItemPerPage ) ;    
    $paged_data = retrieveData ( $page ) ;
    
    /* Print the data */
    echo "<table style=\"width: 100%\" border=\"1\"><tr><th style=\"background-color: #00FFAA\">Items</th></tr>" ;
    
    /* Loop through the paged-data */
    foreach ( $paged_data as $item )
        echo "<tr><td style=\"background-color: #EEEEEE\">$item</td></tr>" ;
    
    /* Print the prev/next page link */
    if ( $maxPageNumber > 1 )
    {
        echo "<tr><td style=\"background-color: #00FFFF; text-align: center\">" ;
        
        /* We can go backward to previous page */
        if ( $page > 1 )
            echo "<a href=?p=" . ( $page - 1 ) . ">Prev. Page</a>  " ;
        
        /* We can go forward to the next page */
        if ( $page < $maxPageNumber )
            echo "<a href=?p=" . ( $page + 1 ) . ">Next Page</a>" ;
        
        echo "</td></tr>" ;
    }
        
    echo "</table>" ;
?>


That's it. Hope you enjoy the tutorial and can gain benefit from it. Remember, this is a very simple one. You can also use another way to do paging by enabling user to go to certain page directly. Or, if you are a professional programmer wannabe, don't worry, there are many frameworks out there that handle all the nifty-gritty in doing beautiful paging mechanism.

Happy code fellas....

1 comment: