Zend - The PHP Company




Abstraction Layers

Add Code


Object Database Abstraction  

Type: class
Added by: simon622
Entered: 11/07/2002
Last modified: 07/12/2001
Rating: - (fewer than 3 votes)
Views: 6328
An object orientated database absraction layer. Meant for use with mySQL. Supports persistant and non persistant connections, error handling and customised logging. Designed to separate application from database logic. Returns all required elements, result resources, rows and field sizes and names.


<?PHP

/*************************
Author: Simon Johnson
Date: 01/07/2002
**************************/

/*************************
This class was written specifically for my needs, acts as an abstraction,
to separate database connectivity from application logic, returns very little in the way of output,
unless specified in the query method - Nice formatted table(Easy reference), Do not use as output, just
a guide, the table is poor for large datasets!
I didnt want textual output everywhere,so have used logs to display relavent info,
alot more graceful! PLEASE REMEBER TO SET REQUIRED FILE PERMISSIONS ON SERVER FOR LOGS.
YOU MUST HAVE ROOT ACCESS TO ALLOW AUTO CREATE OF LOGS
*************************/

/*************************
PRIVATE: Private attributes not supported in php, so
leave out get accessors where this key word is. You cen enforce change using
set if required
**************************/

/*TODO: Create separate file writer object for error handling*/
/*TODO: Support transactions and pointers.+better rows handlers*/

class Dbase
{

//CLASS ATTRIBUTES

/*************
If you want to explicitly set connection details do so below
************/

var $hostname;
var 
$username;
var 
$password;
var 
$dbname;

/*****************************************
To turn error and action reporting on, set to one, else leave blank.
If it is set on, create a directory /logs, in the same filesystem as the class.
Create two files, action_log.txt and dbase_log.txt.
*******************************************/
var $err_rep=1;

var 
$dbtype;
var 
$qryrows;
var 
$qryfields;
var 
$tblname;
var 
$error;
var 
$conn//PRIVATE
var $action;
var 
$querystring;
var 
$qryresult;
var 
$try//PRIVATE

/*******************************************
FULL SET OF ACCESSOR METHODS TO ENCOURAGE ENCAPSULATION AND DATA HIDING
********************************************/

/*******
SETTERS
********/
function setDbname($newdbname)
    {
     
$this->dbname=$newdbname;
    }
function 
setTry($newtry)
    {
     
$this->try=$newtry;
    }
function 
setDbtype($newdbtype)
    {
     
$this->dbtype=$newdbtype;
    }
function 
setHostname($newhostname)
    {
     
$this->hostname=$newhostname;
    }
function 
setUsername($newusername)
    {
     
$this->username=$newusername;
    }
function 
setPassword($newpassword)
    {
     
$this->password=$newpassword;
    }
function 
setQryrows($newqryrows)
    {
     
$this->qryrows=$newqryrows;
    }
function 
setQryfields($newqryfields)
    {
     
$this->qryfields=$newqryfields;
    }
function 
setTblname($newtblname)
    {
     
$this->tblname=$newtblname;
    }
function 
setError($newerror)
    {
        
$this->error=$newerror;
        
$date date("j m Y");
        if (
$this->err_rep=="1")
            {
                
$filelocation="dbase_log.txt";
                
$newfile fopen($filelocation,"a+");
                
$add "n"."$this->error$date";
                
fwrite($newfile$add);
                
fclose($newfile);
            }
        else
            {
                
//Do nothing
            
}

    }
function 
setConn($newconn)
    {
     
$this->conn=$newconn;
    }
function 
setAction($newaction)
    {
     
$this->action=$newaction;
     
$date date("G:i : j m Y");
     if (
$this->err_rep=="1")
         {
             
$filelocation="action_log.txt";
             
$newfile fopen($filelocation,"a+");
             
$add "n"."$this->action$date";
             
fwrite($newfile$add);
             
fclose($newfile);
         }
     else
         {
            
//Do nothing - This needs addressing, not brilliant coding!
         
}
    }
function 
setQuerystring($newquerystring)
    {
     
$this->querystring=$newquerystring;
    }

function 
setQryresult($newqryresult)
    {
     
$this->qryresult=$newqryresult;
    }

function 
setErr_rep($newerr_rep)
    {
     
$this->err_rep=$newerr_rep;
    }

/********
GETTERS
********/

function getDbname()
    {
     return 
$this->dbname;
    }
function 
getDbtype()
    {
     return 
$this->dbtype;
    }
function 
getHostname()
    {
     return 
$this->hostname;
    }
function 
getUsername()
    {
     return 
$this->username;
    }
function 
getPassword()
    {
     return 
$this->password;
    }
function 
getQryrows()
    {
     return 
$this->qryrows;
    }
function 
getQryfields()
    {
     return 
$this->qryfields;
    }
function 
getTblname()
    {
     return 
$this->tblname;
    }
function 
getError()
    {
     return 
$this->error;
    }
function 
getAction()
    {
     return 
$this->action;
    }
function 
getQuerystring()
    {
     return 
$this->querystring;
    }
function 
getQryresult()
    {
     return 
$this->qryresult;
    }
function 
getErr_rep()
    {
     return 
$this->err_rep;
    }

/******************************
OPERATOR FUNCTIONS
******************************/

function SetUp($hostname,$username,$password,$dbname)
    {

/*******************************
INCASE SOMETHING GOES WRONG WITH FILE WRITER, CHECK LOG SET-UP
********************************/

    
if ($this->err_rep==1)
        {
            if (
file_exists("action_log.txt"))
                {
                    
$this->setAction("NEW INSTANCE");
                }
            else
                {
                    echo
"No files Found, first run detected, attempting to create log files, re-instantiate object for populated firstrun logs";
                }
        }
    else
        {}

        
$this->setHostname($hostname);
        
$this->setUsername($username);
        
$this->setPassword($password);
        
$this->setDbname($dbname);
    }

function 
Connect($type)//THIS PARAMETRE IS REQUIRED!! EITHER  1 or 0
    /*****************
    Will return a message if theres an error, get the message in the child
    like so: '$message=$con->Connect()'
    Or use the accessor '$message=$con->GetError()', or just check the log!
    ********************/
    
{
    if((
$this->username=="")||($this->password=="")||($this->hostname==""))
        {
            
$this->setError("You have failed to insert either your' username, hostname or password");
        }
    else
        {
            switch(
$type)
                {
                    case 
"1":
                        
$this->conn = @mysql_pconnect($this->hostname,$this->username,$this->password);
                    break;
                    default:
                        
$this->conn = @mysql_connect($this->hostname,$this->username,$this->password);
                    break;
                }
                if (
$this->conn)
                    {
                        
$this->setAction("Connection Made to Database on $this->hostname");
                        
$this->setTry(mysql_select_db($this->dbname));
                        if(
$this->try)
                            {
                                
$this->setAction("Successfully communicating with database: $this->dbname");
                            }
                        else
                            {
                                
$this->setAction("Connection made but cannot talk to database");
                                
$this->setError("This certainly shouldn't happen!!");
                            }
                    }
                else
                {
                    
$this->setAction("Database Connection Attempt Failed See Error log");
                    
$this->setError("Database Connection Error,reason: Connection remains in scope");
                }
            }return 
$this->error;
    }

function 
Disconnect()
    {
        if(
$this->conn)
            {
                
$this->try=mysql_close($this->conn);
                
$this->setConn(mysql_free_result($this->qryresult));
                if(
$this->try)
                    {
                        
$this->setAction("Database Connection closed");
                    }
                else
                    {
                        
$this->setAction("Attempted to close Database Connection however it is Persistant");
                        
$this->setError("Database Remains Open");
                    }
            }
        else
            {
                
$this->setAction("Database connection could not be made, so disconnection is irrelavent");
                
$this->setError("Database Remains Closed");
            }
    }

function 
Query($string$display)
    {

    if(
$this->conn)
        {
            
$this->setQuerystring($string);
            
$this->setQryresult(mysql_db_query($this->dbname$this->querystring));
            
$this->setQryrows(mysql_num_rows($this->qryresult));
            
$this->setQryfields(mysql_num_fields($this->qryresult));

            if(
$this->qryresult)
                {
                    
$this->setAction("Query Execution Success");
                    if (
$display=="1")
                        {
                            
$this->setAction("Attempting to display query results");
                            
$c=$this->qryfields;
                            
$r=$this->qryrows;
                            echo
"<table border=1><tr>";
                                for (
$i 0$i $c$i++)
                                    {
                                        
$cols mysql_field_name($this->qryresult$i);
                                        
$cols=strtoupper($cols);
                                        echo 
"<td border=1><b><font face=arial size=1>$cols</b><br>";
                                            for (
$g 0$g $r$g++)
                                            {
                                                
$rows mysql_result($this->qryresult$g$cols);
                                                echo 
"<font face=arial size=1><br>$rows<br><br>";
                                            }
                                    }
                            echo
"</font></table>";

                        }
                        else
                        {
                            
$this->setAction("No Display of query requested, populating result resource");
                        }
                }
                else
                    {
                        
$this->setAction("Query Execution Failure");
                        
$this->setError("Query Execution Error");
                    }
            }
    else
        {
            
$this->setAction("Credentials could not be verified or connection instance not called");
            
$this->setError("Bad credentials or connection instance not called");
        }

    }

}

?>


Usage Example


<?
require("dbase.class.php");
$con = new Dbase();
$con -> SetUp("Localhost","Username","password","shop");
$con -> Connect();
$string"select * from shop";

/*Adding the 1 as the second parameter,
automatically returns a formatted table.
*/

$con -> Query($string,1);
$result=$con->getQryresult();
$numOfRows=$con->getQryrows();
$con->Disconnect();
?>


Rate This Script





Search



This Category All Categories