Create Dynamic Database Access Objects

Some simple PHP that makes for a surprisingly robust script

<?php
require_once( "DB.php" );
$dsn = 'mysql://root:password@localhost/books';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }

class DBRecord
{
  var $h;

  public function DBRecord( $table, $id )
  {
   global $db;
   $res = $db->query( "SELECT * from $table WHERE id=?", array( $id ) );
   $res->fetchInto( $row, DB_FETCHMODE_ASSOC );
 $this->{'h'} = $row;
  }
  public function _ _call( $method, $args )
  {
 return $this->{'h'}[strtolower($method)];
  }
  public function _ _get( $id )
  {
 return $this->{'h'}[strtolower($id)];
  }
}
?> 
 
 
 

A simple script that tests the database access script
<?php require_once( "DBrecord.php" );
 $rec = new DBRecord( "author", 2 );
print $rec->Name()."\n";
?>

PHP 5 represents a substantial upgrade in terms of object-oriented support in the PHP language. Along with a number of upgrades in performance, PHP 5 has a major upgrade in the ability to create dynamic classes. These are classes where the methods and attributes change from object to object. This can be very handy in building database applications.