PHP
  Home arrow PHP arrow Page 5 - Working with MySQL and Sessions to Ser...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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? 
PHP

Working with MySQL and Sessions to Serialize Objects in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 12
    2006-06-20

    Table of Contents:
  • Working with MySQL and Sessions to Serialize Objects in PHP
  • The basics of automated object serialization: using objects and sessions
  • Combining objects and sessions: defining a session handling class
  • Another implementation of object serialization: saving objects to MySQL tables
  • The complete list of classes for the example

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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


    Working with MySQL and Sessions to Serialize Objects in PHP - The complete list of classes for the example


    (Page 5 of 5 )

    Finally, for the sake of completeness, below I listed all the classes that I used for constructing the previous example:

    // define 'User' class
    class User{
        var $name;
        var $address;
        var $email;
        function User($userData=array()){
            if(!is_array($userData)){
                trigger_error('User data must be an
    array!',E_USER_ERROR);
            }
            foreach($userData as $property=>$value){
                if($property==''||$value==''){
                    trigger_error('Invalid values for user
    data!',E_USER_ERROR);
                }
                $this->{$property}=$value;
            }
        }
        // obtain user name
        function getName(){
            return $this->name;
        }
        // obtain user address
        function getAddress(){
            return $this->address;
        }
        // obtain user email
        function getEmail(){
            return $this->email;
        }
    }
    // define 'ObjectSerializer' class
    class ObjectSerializer{
        function ObjectSerializer(){}
        function getSerializedObj($obj){
            if(!is_object($obj)){
                trigger_error($obj.'input parameter must be an
    object!',E_USER_ERROR);
            }
            return serialize($obj);
        }
        function getUnserializedObj($data){
            if(!is_string($data)){
                trigger_error($data. 'must be a
    string!',E_USER_ERROR);
            }
            return unserialize($data);
        }
    }
    // define 'MySQL' class
    class MySQL {
        var $conId; // connection identifier
        var $host; // MySQL host
        var $user; // MySQL username
        var $password; // MySQL password
        var $database; // MySQL database
        // constructor
        function MySQL($options=array()){
            // validate incoming parameters
            if(count($options)>0){
                foreach($options as $parameter=>$value){
                    if(empty($value)){
                        trigger_error('Invalid parameter
    '.$parameter,E_USER_ERROR);
                    }
                    $this->{$parameter}=$value;
                }
                // connect to MySQL
                $this->connectDB();
            }
            else {
                trigger_error('No connection parameters were
    provided',E_USER_ERROR);
            }
        }
        // connect to MYSQL server and select database
        function connectDB(){
            if(!$this->conId=mysql_connect($this->host,$this-
    >user,$this->password)){
                trigger_error('Error connecting to the
    server',E_USER_ERROR);
            }
            if(!mysql_select_db($this->database,$this->conId)){
                trigger_error('Error selecting
    database',E_USER_ERROR);
            }
        }
        // perform query
        function query($query){
            if(!$this->result=mysql_query($query,$this->conId)){
                trigger_error('Error performing query
    '.$query,E_USER_ERROR);
            }
            // return new Result object
            return new Result($this,$this->result); 
        }
    }
    // define 'Result' class
    class Result {
        var $mysql; // instance of MySQL object
        var $result; // result set
        function Result(&$mysql,$result){
            $this->mysql=&$mysql;
            $this->result=$result;
        }
        // fetch row
        function fetchRow(){
            return mysql_fetch_array($this->result,MYSQL_ASSOC);
        }
        // count rows
        function countRows(){
            if(!$rows=mysql_num_rows($this->result)){
                return false;
            }
            return $rows;
        }
        // count affected rows
        function countAffectedRows(){
            if(!$rows=mysql_affected_rows($this->mysql->conId)){
                trigger_error('Error counting affected
    rows',E_USER_ERROR);
            }
            return $rows;
        }
        // get ID from last inserted row
        function getInsertID(){
            if(!$id=mysql_insert_id($this->mysql->conId)){
                trigger_error('Error getting ID',E_USER_ERROR);
            }
            return $id;
        }
        // seek row
        function seekRow($row=0){
            if(!mysql_data_seek($this->result,$row)){
                trigger_error('Error seeking data',E_USER_ERROR);
            }
        }
        function getQueryResource(){
            return $this->result;
        }
    }

    To wrap up

    We’re done now. Over this series, I covered not only the fundamentals of object serialization in PHP, but also some advanced topics, such as the implementation of the magic “__sleep()” and “__wakeup()” functions, and the usage of objects in sessions. Finally, I completed the series by demonstrating how to store serialized objects in MySQL tables, which makes me believe that you have enough code to keep you experimenting for many hours. As usual, see you in the next PHP tutorial!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · In this last part of the series, you'll learn how to save serialized objects to...
       · Hi.I'm following this tutorial butmay be I found a mistake.I think that you...
       · Hello friend,I'm glad to know my PHP articles have been useful to you, so I...
       · Thank you very much for everything. Your code is clean and logical. I love it. You...
       · Hi Sig again,Well, I'd like to thank you again for the kind comments on my PHP...
       · The previous tutorial referred to is, presumably, <a...
       · I may be missing something, but including the whole class definition in every file...
       · is there a reason why you don't run mysql_real_escape_string() on the serialized...
       · Hello Lucas,Thank you for your posting your comments on my PHP article. Your...
     

       

    PHP ARTICLES

    - Using Aliases and the Autoload Function with...
    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Sub Classing Exceptions in PHP 5
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT