WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
Internet Security Software
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
פרייסז - הכח לקנות עובר לידיים שלך
Texas Holdem Poker Evangelists

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : Demo of Alternate Pagination Paradigm (Paging)
Categories : PHP, User Interface, Sessions Click here to Update Your Picture
Dave Silvia
Date : Nov 14th 2006
Grade : 3 of 5 (graded 5 times)
Viewed : 9192
File : 4529.zip
Images : Image 1
Search : More code by Dave Silvia
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 
 

This is a demo of a model for pagination that differs from others. It has many features that distinguish it from other methodologies, not the least of which is multiple selection of items in the pages. Another feature is that it does not suffer the limitations of html requests lengths, since it uses sessions. Also, it does not go to the database 'well' for each page. Typically, for a given set of access parameters, it only accesses the database once, caching away the results in a session variable. Paging is thus more fluid. It also uses HTML form submit buttons, in conjunction with a select for page 'jumps', to page through the document as opposed to hyperlinks. This makes for cleaner code in general.

The demo consists of 5 files: A driver (simulates the caller in a website hierarchy); The paginator code; The strings that PHP prints to construct the HTML page; The processor (simulates the final processing in a website hierarchy); The database (simulates, say, a MySQL database contents). These are paginationDriver.php, pagination.php, printStings.php, process.php, and database.php respectively. The strings that create the HTML code are in a separate file so as not to obscure the PHP pagination logic in pagination.php. This is not really necessary, but it does make the code easier to read. Do as you wish with your own implementation.

The code logic revolves around a set of variables: $jobTitle; $sortOrder; $sequence; $pageLen; $curPage; $totalCount; $itemList. There are, of course, others, but these are really the important ones. The first three, $jobTitle, $sortOrder, $sequence, are selector categories in the menu. The value returned by these says how to access the data. $pageLen is the number of items to show per page. $curPage begins as the page last viewed by the user and in the process of the pagination logic changes to the page which will be viewed. $curPage is used in 2 places in the code as an index into the selected $itemList in conjunction with $pageLen. Be careful with where values are assigned to $curPage! Reassigning to the value of the page which will be viewed in the wrong place in the code execution will break the code! $totalCount is the total number of items currently selected from the database. $itmeList is the actual list selected from the database. It only changes when the user specifies new criteria through the selector categories in the menu.

One other variable controls how the paging takes place, that is $btnVal. In the form there are 5 buttons: Next; Prev; Go To; Process Selections; Cancel. These are all assigned the name 'btnVal'. On reentry into pagination.php, this value is examined. If it is Next, Prev, or Go To, a value is assigned to $curPage indicating the page which will next be seen by the user. If the value is Next, $curPage is incremented unless it is already equal to the last page, in which case it is set to 1. If the value is Prev, $curPage is decremented unless it is already equal to 1, in which case it is set to the last page. If the value is Go To, $curPage is simply set to the value returned in the select as 'pageNum'. This is one of the unique properties of this methodology, it allows the user to page backwards, forwards, or 'jump' to any page. Most methods that use hyperlinks only allow a proximity range for 'jumps'. Of course, if you have a very large database that can select a huge number of pages, another algorithm needs to be used, such as every other, 3rd, 4th, etc. page., but still, it's more flexible than the proximity range method.

As the user pages through the selections, he may choose to have one of the selections processed by choosing the select next to the first field in the table row. This is saved in the $itemList as a boolean (true, false) and thus the user choices are preserved from page to page. This is another feature where this design differs from most. In the hyperlink method, the user generally selects a link in the item he wishes to process. This then goes to another page to process the choice. This means that the user's train of thought is interrupted, not to mention the continuity of the paging process. It also means that processing code must be called for each selection individually. With the method outlined in the demo, all selections are processed at the same time, i.e., when the user has finished making choices.

The final 2 elements in the paradigm are how the user chooses to terminate their browse of the selections: process or cancel. These are the other two buttons used in the form that have the name 'btnVal'. On reentry into pagination.php, $btnVal is checked to see if it is a termination value, i.e. 'Process Selections' or 'Cancel'. Cancel is simple, just destroy the session and return to the web page in the hierarchy that called the paginator code. The other choice is more involved but not overly so. The model just checks for at least one 'true' in the $itemList. If one is found, we proceed to the processor code, if not, we simply return to pagination.php to let the user either continue or cancel.

The last step is, of course, doing whatever processing is required for the user's selections. The stub, process.php, illustrates this step.

Of course, there are more algorithms which can be used to adapt this paradigm to a specific use. One obvious one is the case of an extremely large database with hundreds (thousands?) of entries. An algorithm might be put in place here that ascertains the total number of entries and chops them into manageable sections, going back to the database 'well' whenever the next page to be viewed is outside the current cache. But the basic principles of reduced database access and multiple selection are still in force.

To see a 'live' implementation of this paradigm, visit http://www.wxcodex.net/. This is the site for which I developed the design.

Hope you find this useful!;)

thx,
Dave S.
Dave Silvia


You can find all of the files attached to this code example (at the begining of the example).

pagination.php
<?php
/*
*  (c) 2006, D.E. Silvia, All rights reserved.
*  This code is available for use for non-commercial purposes. It may be used
*  at any website, conmercial and private, but may not be incorporated into
*  a commercial product without the express consent of the author.
*  Free to distribute as long as this copyright information remains intact.
*  dsilvia@mchsi.com
*
*/

   
$jobTitle=$_REQUEST['jobTitle'];
   
$sortOrder=$_REQUEST['sortOrder'];
   
$sequence=$_REQUEST['sequence'];
   
$mySessName=session_name();
   
$mySessID=(isset($_REQUEST[$mySessName])) ? $_REQUEST[$mySessName] : rand();
   
session_name($mySessName);
   
session_id($mySessID);
    @
session_start();
    if(isset(
$_REQUEST['reset']))
    {
        unset(
$_SESSION['itemList']);
    }
   
$pageLen=8;
   
$curPage=(isset($_REQUEST['curPage'])) ? $_REQUEST['curPage']+0 : 1;
    if(isset(
$_SESSION['itemList'])) $itemList=$_SESSION['itemList'];
    if(isset(
$_SESSION['totalCount'])) $totalCount=$_SESSION['totalCount'];
   
$homeScript=(isset($_SESSION['homeScript'])) ? $_SESSION['homeScript'] : '/index.html';
    if(isset(
$_REQUEST['itemSelected']))
    {
       
$itemSelected=$_REQUEST['itemSelected'];
       
$k=0;
        for(
$i=($curPage-1)*$pageLen; $i < (($curPage-1)*$pageLen)+$pageLen; $i++)
        {
            if(
$i == $totalCount) break;
           
$itemList[$i]['Selected']=($itemSelected[$k] == '1') ? true : false;
           
$k++;
        }
       
$_SESSION['itemList']=$itemList;
    }
    if(isset(
$_SESSION['numPages'])) $numPages=$_SESSION['numPages'];
    if(isset(
$_REQUEST['btnVal'])) $btnVal=$_REQUEST['btnVal'];
    if(isset(
$btnVal) && $btnVal != 'Process Selections' && $btnVal != 'Cancel')
    {
        if(
$btnVal == 'Next')
           
$curPage=($curPage == $numPages) ? 1 : $curPage+1;
        else if(
$btnVal == 'Prev')
           
$curPage=($curPage == 1) ? $numPages : $curPage-1;
        else if(
$btnVal == 'Go To')
           
$curPage=$_REQUEST['pageNum'];
    }

    if(!isset(
$itemList) && (!isset($btnVal) || (isset($btnVal) && $btnVal == 'Continue')))
    {
       
// We haven't been to the database 'well' yet, so we go to fill our data 'bucket'
        // We won't be back unless the user wants to display differently in some way
        //
        // This would typically be a section where we might access a database
        // Here we just use a static array.
        // The database
       
include('database.php');
       
// equivalent to a query, e.g. $demoData=mysql_query("select * from `demoDatabase where ...`;");
        //  and equivalent to a fetch, e.g. while($demoDatum=mysql_fetch_row($demoData))
       
if($jobTitle == 'All') $demoData=$demoDatabase;
        else
        {
            foreach(
$demoDatabase as $dataRow)
            {
                foreach(
$dataRow as $key => $value)
                {
                    if(
$jobTitle == $value)
                    {
                       
$demoData[]=$dataRow;
                        break;
                    }
                }
            }
        }
       
$orderBy=array();
        foreach(
$demoData as $key => $row)
        {
           
$orderBy[$key]=$row[$sortOrder];
        }
        if(
$sequence == 'ASC')
           
array_multisort($orderBy,$demoData);
        else
           
array_multisort($orderBy,SORT_DESC,$demoData);
       
// Okay, we've been to the 'well' and our 'bucket' is full!;)

       
$itemList=$demoData;
       
$totalCount=count($itemList);
       
$numPages=ceil($totalCount/($pageLen*1.0));
       
$_SESSION['itemList']=$itemList;
       
$_SESSION['numPages']=$numPages;
       
$_SESSION['totalCount']=$totalCount;
    }
   
$next=($curPage == $numPages) ? 1 : $curPage+1;
   
$prev=($curPage == 1) ? $numPages : $curPage-1;
   
// This matches, say, jobTitles in a database (enum) which you could fetch
    // See: http://www.weberdev.com/get_example-4525.html
    // Usage from that script would be:
    //    $jobTitles=getEnumVals($host,$user,$password,$db,$table,$field,$sorted=true)
    //
    // Here we use a static array. equivalent to the above
   
$jobTitles=array('Clerk','Manager','Sales Person','Secretary','V.P.','Warehouse Worker');
   
// And add the 'All' which is not in the database.
   
$jobTitles=array_merge(array('All'),$jobTitles);
   
// Get the document strings
   
include('printStrings.php');
   
// Begin the XHTML doc
   
print($docOpenStr);

    if(isset(
$btnVal) && $btnVal == 'Cancel')
    {
       
session_destroy();
        print(
$headCancelStr);
    }
    else if(isset(
$btnVal) && $btnVal == 'Process Selections')
    {
       
$haveSelections=false;
        foreach(
$itemList as $slct)
        {
           
$haveSelections=$slct['Selected'];
            if(
$haveSelections) break;
        }
        if(
$haveSelections) print($headProcessStr);
        else print(
$headLoopBackStr);
        print(
$headCloseStr);
    }
    else
    {
        print(
$headStyleStr.$headCloseStr);
    }

    if(!isset(
$btnVal) || (isset($btnVal) && ($btnVal == 'Go To' || $btnVal == 'Next' || $btnVal= 'Prev')))
    {
        print(
$bodyOpenStr);
        print(
$menu);
        print(
$formOpenStr.$pageCtrlStr.$tableOpenStr.$tableBodyStr.$tableCloseStr.$formCloseStr);
        print(
$bodyCloseStr);
    }
    print(
$docCloseStr);
?>



CAPTCHA[Image verification]
Categories : PHP, Security, GD image library, Graphics, Sessions
Session Validation Methods (Security Checks)
Categories : PHP, Sessions, Security
Problem passing session variables
Categories : Sessions, PHP
Securing Web Forms with Simple PHP-CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart)
Categories : PHP, Security, GD image library, Sessions
SPL and ITERATOR : examples
Categories : PHP, Object Oriented, PHP Classes, Sessions
GuestBook Light - a plug and play application for any website.
Categories : PHP, Complete Programs, Filesystem, Sessions
multilingual website
Categories : PHP, Languages, Sessions
CSS style switcher
Categories : PHP, CSS, HTML and PHP, Arrays, Sessions
session_cache_limiter -- Get and/or set the current cache limiter
Categories : PHP, PHP Functions, Sessions
Warning: Unknown(): A session is active. You cannot change the session module's ini settings at this time. in Unknown on line 0
Categories : PHP, Sessions, Databases, MySQL
Basic Authentication with sessions
Categories : PHP, Beginner Guides, Authentication, Form Processing, Sessions
Simple Session example
Categories : PHP, Beginner Guides, Sessions
Security, Password lock out after three tries, authorization fails and is logged locked out of account till admin decides he will unlock it.
Categories : Sessions, PHP, MySQL, PHP Options and Info
Form Security - Match A Value For Success
Categories : PHP, Authentication, HTML and PHP, Sessions, Security
Sessions and -enable-trans-sid
Categories : PHP, PHP Configuration, PHP Options and Info, Sessions