PHP
  Home arrow PHP arrow Page 2 - Using the Active Record Pattern with PHP and MySQL
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 the Active Record Pattern with PHP and MySQL
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 10
    2009-03-03


    Table of Contents:
  • Using the Active Record Pattern with PHP and MySQL
  • Building a simple data mapper in PHP
  • Building a basic MySQL abstraction class
  • Inserting database table rows with the active record pattern

  • 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 the Active Record Pattern with PHP and MySQL - Building a simple data mapper in PHP
    ( Page 2 of 4 )

    A good way to start explaining how to use the active record pattern in PHP consists of creating a quick and dirty data mapper class. This class will be tied to a specified MySQL database table to select, insert, update and delete its rows, without having to code any SQL queries.

    That being said, suppose for a moment that there’s a sample “users” table that will be accessed via a data mapper class. According to this scenario, the primitive signature of this class might look similar to this:


    class User{

    private $firstName;

    private $lastName;

    private $email;

    private $table='users';

    public function __construct(){}

    // set first name

    public function setFirstName($firstName){

    $this->firstName=$firstName;

    }

    // set last name

    public function setLastName($lastName){

    $this->lastName=$lastName;

    }

    // set email

    public function setEmail($email){

    $this->email=$email;

    }

    // fetch row

    public function fetch($id){

    if(!$row=mysql_query("SELECT * FROM $this->table WHERE id='$id'")){

    throw new Exception('Error fetching row');

    }

    return $row;

    }

    // insert row

    public function insert(){

    if(!mysql_query("INSERT INTO $this->table (firstname,lastname,email) VALUES ($this->firstName,$this->lastName,$this->email)")){

    throw new Exception('Error inserting row');

    }

    }

    // update row

    public function update($id){

    if(!mysql_query("UPDATE $this->table SET firstname='$this->firstName,lastname=$this->lastName,email=$this->email WHERE id='$id'")){

    throw new Exception('Error updating row');

    }

    }

    // delete row

    public function delete($id){

    if(!mysql_query("DELETE FROM $this->table WHERE id='$id'")){

    throw new Exception('Error deleting row');

    }

    }

    }


    As you can see, the above “User” class implements a set of straightforward methods for selecting inserting, updating and deleting rows from a fictional “users” MySQL database table. Notice that each of these operations works with only one row at time, in this way behaving like a simple interface that permits you to access data in the table.

    Now that you hopefully understood how the previous data mapper class does its thing, here’s a basic example that demonstrates its usage in a concrete case. Take a look at the code sample below:


    try{

    $user=new User();

    // set first name

    $user->setFirstName('Alejandro');

    // set last name

    $user->setlastName('Gervasio');

    // set email

    $user->setEmail('alejandro@domain.com');

    // insert row

    $user->insert();


    // set first name

    $user->setFirstName('Alejandro');

    // set last name

    $user->lastName('Gervasio');

    // set email

    $user->setEmail('alex@domain.com');

    // update row

    $user->update(1);

    // delete row

    $user->delete(1);

    }

    catch(Exception $e){

    echo $e->getMessage();

    exit();

    }


    As shown above, the previous sample class uses the active record pattern to insert, update and delete a single row from the corresponding “users” MySQL table. It's easy to see here how the pattern permits us to perform these tasks in an intuitive manner, even when no SQL statements have been explicitly coded.

    So far, everything looks good. At this point, you've learned how to build a simple class with PHP 5 which utilizes the active record pattern for interacting with a selected MySQL table. However, as I expressed at the beginning, it’s also possible to achieve a decent level of SQL abstraction without using a data mapper class like the one shown before.

    In fact, it’s perfectly feasible to create a simple database abstraction class that performs selects, updates, deletions, and so forth, without directly writing any SQL clauses. And this is exactly what I’m going to do in the next section, so you can understand more clearly how the active record pattern can be applied by using a slightly different approach.

    In order to learn how this brand new PHP class will be defined, please click on the link that appears below and read the next few lines.



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

       

    PHP ARTICLES

    - Adding Ordering and Grouping Clauses to the ...
    - 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...





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