RE: Database Class Help

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Ian Barnes wrote:
> We have a database class that we want to use to connect to multiple
> databases at the same time using different variables.


>  function db($db_host, $db_user, $db_pass, $db_name) {
>    $this->dbh = @mysql_pconnect($db_host, $db_user, $db_pass);
>    $this->select_db($db_name);
>  }

> Now that happens is when I try and do the query for db1, I get told that
> db2.table1 doesn't exist. I can swop anything around and it doesn't seem 
> to work for one of the classes.

> Does anyone have any idea as to why this is happening?

You didn't specify but I guess all your databases are on the same server.

When accessing multiple databases on the same server using multiple
instances of a class, you need to make multiple connections to the server.

By default PHP creates only ONE connection to a server and the database you
select is linked to the connection. So instantiating another instance will
use the previous established connection and change the database.

To force a new connection, you need to use mysql_connect() instead of
mysql_pconnect(). When using mysql_connect() you can specify:

$this->dbh = @mysql_connect($db_host, $db_user, $db_pass, true);

[quote from="PHP manual"]
resource mysql_connect ( [string server [, string username [, string
password [, bool new_link [, int client_flags ]]]]] )
[/quote]

Which will force a new connection. By default PHP will use a connection
which have already been established.

Take care when doing this as each time you instantiate a class a new
connection to the database will be created adding additional load on your
database which can cause a denial of service.

I normally store a list of connections to servers and databases in a
variable which can be accessed by the script. Every time I instantiate a new
instance of my database class I first make sure that a connection to that
server and database does not already exist. If it does exist then I call
mysql_connect() without the true for new_link otherwise I call
mysql_connect() with the true for new_link.

The downside of this is that you do not have persistent connections which
last beyond the end of the script.

Hope it helps

Albert



-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.1.362 / Virus Database: 267.13.10/189 - Release Date: 2005/11/30
 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux