PHP
  Home arrow PHP arrow Page 4 - Using Visitor Objects with MySQL Data Sets in PHP 5
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Using Visitor Objects with MySQL Data Sets in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 9
    2006-08-16


    Table of Contents:
  • Using Visitor Objects with MySQL Data Sets in PHP 5
  • Visiting database result sets: establishing an interaction between visitors and MySQL
  • Revealing the anatomy of a visitor class: creating visitor objects
  • Completing the round trip: defining the structure of a pagination class

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Using Visitor Objects with MySQL Data Sets in PHP 5 - Completing the round trip: defining the structure of a pagination class
    ( Page 4 of 4 )

    As I said in the section that you just read, the primary purpose of creating a visitor class was defining a model of interaction between the prior "Result" class and a data set pagination system. Obviously, this last component remains undefined as yet. Below I have listed the source code of a pagination class which I have been using frequently when I developed a series of articles aimed at discussing the pagination of result sets with PHP.

    Here is how this pagination class looks:

    // define 'Pager' class
    class Pager{
        private $db;
        private $query;
        private $numRecs;
        private $output='';
        public function __construct($db,$query,$numRecs=10){
            // validate query
            if(!preg_match("/^SELECT/",$query)){
                throw new Exception('Invalid query. Must begin with
    SELECT');
            }
            $this->query=$query;
            // validate number of records per page
            if(!is_int($numRecs)||$numRecs<0){
                throw new Exception('Invalid number of records');
            }
            $this->numRecs=$numRecs;
            $this->db=$db;
        }
        public function displayRecords($page){
            // use visitor for obtaining number of rows in result set
            $resultObj=$this->db->query($this->query);
            $mysqlResultVisitor=new MySQLResultVisitor;
            $resultObj->acceptVisitor($mysqlResultVisitor);
            // calculate total number of records via Visitor object
            $totalRecs=$mysqlResultVisitor->visitMySQLResult
    ($resultObj);
            // calculate number of pages
            $numPages=ceil($totalRecs/$this->numRecs);
            if(!preg_match("/^d{1,2}$/",$page)
    ||$page<1||$page>$numPages){
                $page=1;
            }
            // get result set
            $resultObj=$this->db->query($this->query.' LIMIT '.
    ($page-1)*$this->numRecs.','.$this->numRecs);
            while($row=$resultObj->fetchRow()){
                foreach($row as $key=>$value){
                    $this->output.=$value.' ';
                }
                $this->output.='<br />';
            }
            // create page links
            $this->output.='<div>';
            // create previous link
            if($page>1){
                $this->output.='<a href="'.$_SERVER['PHP_SELF'].'?
    page='.($page-1).'">&lt;&lt;Previous</a>&nbsp;';
            }
            // create numerated links
            for($i=1;$i<=$numPages;$i++){
                ($i!=$page)?$this->output.='<a href="'.$_SERVER
    ['PHP_SELF'].'?page='.$i.'">'.$i.'</a>&nbsp;':$this-
    >output.=$i.'&nbsp;';
            }
            // create next link
            if($page<$numPages){
                $this->output.='&nbsp;<a href="'.$_SERVER
    ['PHP_SELF'].'?page='.($page+1).'">Next&gt;&gt;</a>';
            }
            $this->output.='</div>';
            // return final output
            return $this->output;
        }
    }

    Certainly, I'm not going to discuss the logic of the class listed above, simply because it's out of the scope of this article. But it's clear to see that this class is capable of displaying paginated record sets returned by MySQL, in addition to including the so-called "page links."

    Now, once you have a good idea of how this paging class works, please have a look at the following fragment of code, excerpted from its "displayRecords()" method:

    // use visitor for obtaining number of rows in result set
    $resultObj=$this->db->query($this->query);
    $mysqlResultVisitor=new MySQLResultVisitor;
    $resultObj->acceptVisitor($mysqlResultVisitor);
    // calculate total number of records via Visitor object
    $totalRecs=$mysqlResultVisitor->visitMySQLResult($resultObj);

    Here's where the real action takes place! If you examine the above code snippet, you'll realize that this "Pager" class uses the mentioned visitor object to determine the number of rows returned by a SELECT query, and based on this parameter, it displays chunks of database records.

    In other words, the visitor in question inspects the previous "Result" class, and retrieves one of the values required for the pagination system to display paginated results. At this stage, the link established between the classes that process data sets and paginate them respectively should be clear to you.

    Okay, having defined all the classes required to implement a comprehensive pagination system, allow me to put all the pieces together. The code listing below shows precisely how all the classes fit each other, after populating a sample "users" database table with some trivial data:

    try{
        // connect to MySQL
        $db=new MySQL(array('host'=>'host','user'=>'user',
    'password'=>'password','database'=>'database'));
        // paginate result set
        $pager=new Pager($db,'SELECT * FROM users',$numRecs=2);
        // display paged result set
        echo $pager->displayRecords($_GET['page']);
    }
    catch(Exception $e){
        echo $e->getMessage();
        exit();
    }

    And finally, the output of the previous script is depicted by the following screen shot:

    Final thoughts

    That covers the topic of using visitors for now. Over this series, I introduced in a friendly fashion the creation and usage of visitor objects in PHP 5. From basic examples of how to utilize these objects, to including them in more complex applications, the learning experience has been hopefully educational.

    Either if you're just starting to enter the arena of pattern-based programming or only refreshing some of its more relevant concepts, I hope this article has been helpful to you.  See you in the next PHP tutorial!



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek