Thursday, August 03, 2006

Pear DB and MDB2

So today I decided to look into standardized classes for DB access so that my sites had more portable code and weren’t tied to a single type of database server. My search led me to the DB and MDB2 Pear modules for PHP. After much reconfiguration of my setup at 1&1 I got Pear and the DB and MDB2 modules installed and running.

The following is a snippit of code that shows the same query run with both modules and gives you a framework for how you can start using it:

require_once("DB.php");
require_once("MDB2.php");

function dump_users( $type )
{
  $dsn = array(
  'phptype'  => 'mysql',
  'hostspec' => 'localhost',
  'database' => 'db_name',
  'username' => 'db_user_name',
  'password' => 'db_user_password'
  );

  if($type == "DB")
  {
    $db = DB::connect($dsn);
    if (PEAR::isError($db)) { die($db->getMessage()); }
    $db->setFetchMode(DB_FETCHMODE_ASSOC);
    $res = $db->query( 'SELECT * FROM users');

    if (PEAR::isError($res)) {
      die($res->getMessage());
    }
    echo ‘<pre>’;
    while( $res->fetchInto( $row ) ) {
      print_R($row);
    }
    echo ‘</pre>’;
  } else if($type == "MDB2") {
    $mdb2 =& MDB2::connect($dsn);
    if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); }

    $res = $mdb2->query( 'SELECT * FROM users');

    // Always check that result is not an error
    if (PEAR::isError($res)) {
      die($res->getMessage());
    }

    echo ‘<pre>’;
    while ($row = $res->fetchRow(MDB2_FETCHMODE_ASSOC)) {
      print_R($row);
    }
    echo ‘</pre>’;
  }
}

dump_users('DB');
dump_users('MDB2');

Obviously you need to set the settings for the above $dsn variable as well as execute a valid query. To read more about these modules you can check out their respective pages: DB and MDB2*.

* When installing MDB2, you must also install the driver for your respective database application such as mdb2_driver_mysql. You can find all the drivers listed here.

No comments: