MySQL database abstraction class in PHP

31 Jan

Introduction

A MySQL database abstraction class, which makes database handling easier and object-oriented.

The class:

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>");
}
}

<span id="more-41"></span>

/*
** A method which connects to the server. This cannot be called statically.
** @return: boolean
*/

function connect()
{
if($this-&gt;link=mysql_connect($this-&gt;server,$this-&gt;user,$this-&gt;pass,true))
if(mysql_select_db($this-&gt;db,$this-&gt;link))
return true;
if(is_resource($this-&gt;link))
print("&lt;div class=\"error-box\"&gt;".mysql_error($this-&gt;link)."&lt;/div&gt;");
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-&gt;result=mysql_query($query,$this-&gt;link) or die("&lt;div class=\"error-box\"&gt;".mysql_error($this-&gt;link)."$query&lt;/div&gt;");
}
else
{
if($this-&gt;result=mysql_query($query,$this-&gt;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-&gt;result,$type);
}

/*
** Returns the no. of rows returned
*/

function num_rows()
{
return mysql_num_rows($this-&gt;result);
}

/*
** Frees the memory of the resultset
*/

function free_r()
{
mysql_free_result($this-&gt;result);
}

/*
** Returns the last insert ID, for an auto_increment field
*/

function insert_id()
{
return mysql_insert_id($this-&gt;link);
}

/*
** Closes the MySQL connecttion
*/

function close()
{
mysql_close($this-&gt;link);
}
}

The example usage:

$db = new DB("server.com","admin","pass","customer_db");
$sql = "SELECT * FROM customers";
$db-&gt;query($sql);
// Number of rows returned
printf("The number of rows returned = %d \n&lt;br/&gt;",$db-&gt;num_rows());

while($row=$db-&gt;fetch_rows())
{
printf(‘$row[0] = %s\n’,$row[0]);
}

Or for further references, check out the following resources:

No comments yet

Leave a Reply