MySQL database abstraction class in PHP
31 Jan
Introduction
A MySQL database abstraction class, which makes database handling easier and object-oriented.
The class:
{
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->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:
Or for further references, check out the following resources:


No comments yet