Thread: Class Issue
View Single Post
  #3 (permalink)  
Old 10-01-09, 09:16 AM
carters-site's Avatar
carters-site carters-site is offline
Newbie Coder
 
Join Date: Sep 2009
Location: Moline, IL
Posts: 99
Thanks: 2
Thanked 1 Time in 1 Post
DB
This is one I have used for a long time.

A lot of times on shared servers it already packaged with PHP. I know there is also MDB2 on the PEAR site that you can use also.

I would take the PEAR DB class and wrap it one more level if you want to maintain a constant DB connection (or at least reconnect on DB Host gone away)

Here is one I ripped from a project I did a few years back. It requires PEAR.php and Pear DB.
There is a little extra overhead in doing queries just to establish the connection. this is because I found mysql_ping unreliable at truly determining a MySQL connection resource is valid. Many time mysql_ping will return true but an actual query will result in "DB Server has gone away".

PHP Code:
class qcDB
{
    
/**
    * connect
    * This will establish a connection to that database or check if there is an existing 
    * connection. 
    * 
    * @static
    * @return PEAR DB object $oDB 
    */
    
static public function connect()
    {
        
/* @static $oDB DB Object - connection to database using PEAR DB. */
       
static $oDB null;

      
// Test the connection to make sure it truly is valid. 
      
$xResult $oDB->query("SELECT 1");
      if(
PEAR::isError($xResult)){
         
$oDB null;
      }    
    
       if(
is_null($oDB)){
          
// Since this method is static connect to the Config Object manually
           
$oConfig = new qcConfig();    
   
           
// get the database options
           
$kDBInfo $oConfig->get('database'); 
   
           
// map over values to their DSN values.
           
$kDSN = array(
               
'phptype' => 'mysql',
               
'username' => $kDBInfo['user'],
               
'password' => $kDBInfo['password'],
               
'hostspec' => $kDBInfo['host'],
               
'database' => $kDBInfo['database']
           );
   
           
$oDB DB::connect($kDSN);
         
$oDB->setFetchMode(DB_FETCHMODE_ASSOC);            
      }
        return 
$oDB;
    }
    
    public function 
query($sSQL$aVars = array()){
      
$oDB qcDB::connect();
      return 
$oDB->query($sSQL$aVars);  
   }


Last edited by carters-site; 10-01-09 at 09:19 AM.
Reply With Quote
The Following User Says Thank You to carters-site For This Useful Post:
Zefer (10-01-09)