PHP
  Home arrow PHP arrow Page 4 - Updating and Deleting Database Records with the Active Record Pattern
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

Updating and Deleting Database Records with the Active Record Pattern
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 2
    2009-03-10


    Table of Contents:
  • Updating and Deleting Database Records with the Active Record Pattern
  • Review: fetching and inserting database rows with the active record pattern
  • Updating database rows with the active record pattern
  • Deleting database rows with the active record approach

  • 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


    Updating and Deleting Database Records with the Active Record Pattern - Deleting database rows with the active record approach
    ( Page 4 of 4 )

    If you quickly learned how to use the active record approach to update records of a specified MySQL table, then surely you'll find it even easier to implement a method that deletes them. No, really. But don't take my word for it; look at the improved version of the previous "MySQL" class, which now incorporates a brand new method called "delete()." Here it is:


    class MySQL{

    private $result;

    public function __construct($host='localhost',$user='user',$password='password',$database='database'){

    // connect to MySQL and select database

    if(!$conId=mysql_connect($host,$user,$password)){

    throw new Exception('Error connecting to the server');

    }

    if(!mysql_select_db($database,$conId)){

    throw new Exception('Error selecting database');

    }

    }

    // run SQL query

    public function query($query){

    if(!$this->result=mysql_query($query)){

    throw new Exception('Error performing query '.$query);

    }

    }

    // fetch one row

    public function fetchRow(){

    while($row=mysql_fetch_array($this->result)){

    return $row;

    }

    return false;

    }

    // fetch all rows

    public function fetchAll($table='default_table'){

    $this->query('SELECT * FROM '.$table);

    $rows=array();

    while($row=$this->fetchRow()){

    $rows[]=$row;

    }

    return $rows;

    }

    // insert row

    public function insert($params=array(),$table='default_table'){

    $sql='INSERT INTO '.$table.' ('.implode(',',array_keys($params)).') VALUES (''.implode("','",array_values($params)).'')';

    $this->query($sql);

    }

    // update row

    public function update($params=array(),$where,$table='default_table'){

    $args=array();

    foreach($params as $field=>$value){

    $args[]=$field.'=''.$value.''';

    }

    $sql='UPDATE '.$table.' SET '.implode(',',$args).' WHERE '.$where;

    $this->query($sql);

    }

    // delete one or multiple rows

    public function delete($where='',$table='default_table'){

    $sql=!$where?'DELETE FROM '.$table:'DELETE FROM '.$table.' WHERE '.$where;

    $this->query($sql);

    }

    }


    Now the "MySQL" class includes another method, named "delete()," whose task is to delete one or more rows from a MySQL table. Normally, when using the active record approach, this method would be tasked with removing one database row at a time, but in this case I took the liberty of expanding its functionality so that it can delete multiple records.

    Having explained how the pertinent "delete()" method does its business, here's a short code sample that shows it at work:


    try{

    // connect to MySQL and select a database

    $db=new MySQL('host','user','password','mydatabase');

    // insert new row into sample MySQL table

    $db->insert(array('firstname'=>'Kate','lastname'=>'Johanson','email'=>'kate@domain.com'),'users');

    // delete row from sample MySQL table

    $db->delete('id=4','users');

    }

    catch(Exception $e){

    echo $e->getMessage();

    exit();

    }


    Here you have it. At this point, I've demonstrated with a simple MySQL handling class how to fetch, insert, update, and delete database rows by way of a slightly modified version of the active record pattern. As you saw before, it wasn't necessary to write any SQL statements to perform these typical tasks.

    Finally, feel free to tweak all of the code samples included in this tutorial, so you can get started building your own active record class!

    Final thoughts

    In this second installment of the series, you learned how to implement the active record approach within a basic MySQL abstraction class to update and delete records of a selected database table.

    In the forthcoming part, I'll be enhancing the functionality of this class so that it can perform conditional SELECT statements. Now that you've been told the topic that will be discussed in the next article, you won't want to miss it!



     
     
    >>> 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 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek