Introduction
A MySQL database abstraction class, which makes database handling easier and object-oriented.
The class:
Code: PHP
class DBI
{
var $server;
var $user;
var $pass;
var $db;
var $link;
var $result = null;
/*
** The constrcutor, terminates the script if the connection fails
** @params:
** string $server - the server IP or hostname
** string $user - the username
** string $pass - the password
** string $db - the name of the database to use
*/
function DBI($server,$user,$pass,$db)
{
$this->server = $server;
$this->user = $user;
$this->pass = $pass;
$this->db = $db;
if(!$this->connect())
{
die("<div style=\"text-align:center;border:#a00 solid 1px;padding:4px 1px;margin:0 3px 5px 3px;background:#fdd;color:#a00;font-size:12px;font-family:georgia;letter-spacing:1px;width:90%;\">Server is not reachable ($user@$server)</div>");
}
}
/*
** A method which connects to the server. This cannot be called statically.
** @return: boolean
*/
function connect()
{
if($this->link=mysql_connect($this->server,$this->user,$this->pass,true))
if(mysql_select_db($this->db,$this->link))
return true;
if(is_resource($this->link))
print("<div class=\"error-box\">".mysql_error($this->link)."</div>");
return false;
}
/*
** Queries the DB
** @param:
** string $query - the SQL query
** boolean $debug - terminates on failure if set to true
** @return: boolean - true if successful, else false
*/
function query($query,$debug=false)
{
if($debug)
{
$this->result=mysql_query($query,$this->link) or die("<div class=\"error-box\">".mysql_error($this->link)."$query</div>");
}
else
{
if($this->result=mysql_query($query,$this->link))
return true;
return false;
}
}
/*
** Fetches rows from the resultset
** @param:
** PHP Constant $type - MYSQL_NUM (default) / MYSQL_ASSOC
*/
function fetch_rows($type=MYSQL_NUM)
{
return mysql_fetch_array($this->result,$type);
}
/*
** Returns the no. of rows returned
*/
function num_rows()
{
return mysql_num_rows($this->result);
}
/*
** Frees the memory of the resultset
*/
function free_r()
{
mysql_free_result($this->result);
}
/*
** Returns the last insert ID, for an auto_increment field
*/
function insert_id()
{
return mysql_insert_id($this->link);
}
/*
** Closes the MySQL connecttion
*/
function close()
{
mysql_close($this->link);
}
}
The example usage:
Code: PHP
$db = new DB("server.com","admin","pass","customer_db");
$sql = "SELECT * FROM customers";
$db->query($sql);
// Number of rows returned
printf("The number of rows returned = %d \n<br/>",$db->num_rows());
while($row=$db->fetch_rows())
{
printf('$row[0] = %s\n',$row[0]);
}

