#native_company# #native_desc#
#native_cta#

PHPLib and Multiple Databases Page 3

By Peter Moulding
on November 7, 2000

Expanding PHPLIB

PHPLIB accesses databases through an object created from class DB_Sql.
Db_mysql.inc includes the DB_Sql class as modified for MySQL. We will
extend DB_Sql by adding code to common.php3, after the line that includes
db_mysql.inc.
DB_Sql contains many functions to perform queries. The one we want to
change is:

<?php

 /* public: connection management */

function connect($Database ""$Host ""$User ""$Password "") {

    
/* Handle defaults */

    
if ("" == $Database)

        
$Database $this->Database;

    if (
"" == $Host)

        
$Host     $this->Host;

    if (
"" == $User)

        
$User     $this->User;

    if (
"" == $Password)

        
$Password $this->Password;

 

    
/* establish connection, select database */

    if ( == $this->Link_ID ) {

         
$this->Link_ID=mysql_pconnect($Host$User$Password);

        if (!
$this->Link_ID) {

            
$this->halt("pconnect($Host, $User, $Password) failed.");

            return 
0;

        }

 

        if ([email protected]
mysql_select_db($Database,$this->Link_ID)) {

            
$this->halt("cannot use database ".$this->Database);

            return 
0;

        }

    }

 

    return 
$this->Link_ID;

}

?>



Find the connect() function in your db_mysql.inc (or the .inc for your
database), then copy it in to common.php3 somewhere after the include of
db_mysql.inc. You will have to wrap it in a class definition as described
at the end of this article.
I find the code hard to read. Therefore, the first thing to do is make the copied code
readable:

<?php

/* public: connection management */

function connect($Database ""$Host ""$User ""$Password "") {

    
/* Handle defaults */

    
if ("" == $Database) {

        
$Database $this->Database;

    }

    if (
"" == $Host) {

        
$Host     $this->Host;

    }

    if (
"" == $User) {

        
$User     $this->User;

    }

    if (
"" == $Password) {

        
$Password $this->Password;

    }

    
/* establish connection, select database */

    
if ( == $this->Link_ID ) {

        
$this->Link_ID=mysql_pconnect($Host$User$Password);

        if (!
$this->Link_ID) {

            
$this->halt("pconnect($Host, $User, $Password) failed.");

            return 
0;

        }

        if ([email protected]
mysql_select_db($Database,$this->Link_ID)) {

            
$this->halt("cannot use database ".$this->Database);

            return 
0;

        }

    }

    return 
$this->Link_ID;

}

?>



I indented the code so the levels let me match the brackets, with the
enclosed code. This avoids errors caused by missing brackets. I added
brackets to single lines. PHP lets you get away without brackets around
single lines of code after if statements. As soon as you add extra code,
the shortcut fails. I suggest always use the brackets to avoid errors when
you add code later.