PHP Class: MySQL Database Abstraction

Provides an abstraction layer for MySQL. I use this class in all my coding.

This class is based on the original PHP Base Library distribution, although I’ve eschewed much of the original functionality of the PHPLib version, mostly in order to get “as close to the metal” as possible and provide only those functions which I’ve found I use in all my PHP coding. The main purpose is to encapsulate and simplify the details of connecting to a MySQL database and performing queries.

That’s right, MySQL and MySQL only. I’m not currently interested in developing an all-purpose database abstraction tool; in general, I don’t like to be abstracted that far away from the DB.

This class is designed for a single database; to use it, extend the class in your code, with the given database/user/password you will connect to. For multiple databases, derive additional classes.

You can view the direct source of the class here, or download it in one of the following formats:

Example of usage:

<?php
// Include the class definition file.
require_once(‘class.db.inc’);

// Extend the class with your own database parameters
class DB_Mysql extends DB {
var 
$host ‘host.db.com’;
var 
$database ‘dbname’;
var 
$user ‘username’;
var 
$password ‘password’;
}

// Instantiate the class
$db =& new DB_Mysql;

// Run a SQL query
$db->query(‘SELECT * FROM table’);

// Iterate through the result set (if any)
while ( $db->next_record() ) {
// Retrieve the value for a particular field in the current row
$field $db->f(‘field’);
// etc…
}

?>