Skip to main content

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....

Comments

  1. alhamdulilah... saya izin coba dulu ya suhu.

    ReplyDelete

Post a Comment

Popular posts from this blog

Kisah Nyata Seorang Anak Bernama Andoy dari Filipina

This post is in Bahasa.
Ada seorang anak kecil kelas 4 SD yang selalu mengucap syukur dalam keadaan apapun. Ia tinggal di suatu desa di Negara Filipina. Setiap hari untuk sampai ke sekolahnya ia harus berjalan kaki melintasi daerah yang tanahnya berbatu dan menyeberangi jalan raya yang berbahaya dimana banyak kendaraan yang melaju kencang. Setiap kali berhasil menyeberangi jalan raya tersebut, Andoy selalu mampir sebentar ke Gereja untuk berdoa. Tindakannya ini diamati oleh Pdt. Agaton. Karena merasa terharu dengan sikap Andoy yang lugu dan beriman tersebut. Suatu hari ketika Andoy hendak masuk ke Gereja Pdt. Agaton menyapanya.
Bpk. Pdt : "Selamat pagi Andoy, apa kabarmu? Apakah kamu akan ke sekolah?"
Andoy : "Ya, Bapa Pendeta!" balas Andoy sambil tersenyum.
Bpk.Pdt : "Mulai sekarang saya akan membantu dan menemani kamu menyeberangi jalan raya tersebut setiap kali kamu akan menyeberang.
Andoy : Terima kasih, Bapa Pendeta."
Bpk. Pdt : "sekarang apa yang aka…

Blue Light Filtering with f.lux

Light, one of the very important parts of human living support, has tremendous benefit for us. Light itself is composed of many different rays. One of the components of light, called as blue light, has been known to tamper with our circadian rhythm.

Blue light itself can come from a lot of sources, including the lamp inside your room. However, the source which gives the most impact on people are from electronic devices. In this technology era, it's very hard for us to run away from using electronic devices. Those devices, such as Laptops and Handphones, have tremendously improve our quality of life by making our life easier and more fun through a lot of applications and systems available. Unfortunately, blue light emitted through the screen of those devices can affect our quality of sleep. Some research even advised us not to use our phone a few hours before we are going to sleep to improve our sleep quality.

For tech-savvy people, getting away from devices, especially handphone, …

Needlefish Attack

Just recently, a news spread about a young lady, died due to attack of a Needle fish. The story began when she was having a vacation with her family at Tanjung Karang beach, Makassar, Indonesia. This unfortunate event happened on January 01, 2016.



Liena (39) was soaking her body near the shoreline, whilst suddenly a needlefish jump towards her face. She was not able to dodge because it was too sudden. The fish, known with its long sharp and spear like snout, pierced through her right eyelids. She was then screaming for help. Her husband's family was then run to help her. She was quite badly injured. The wound was so deep that it even pierced through the skull and caused her to vomit blood.

She was brought to the hospital by ambulance to Kabelota Donggala hospital. Nevertheless, the wound was so bad that she eventually could not make it. She passed away in that hospital and the corpse was brought back to Balaikota Palu.



It's highly advised that we are keep being careful when playi…