Re: [PHP-DB] Multiple instances of mysql_connect() in single PHP document.

[email protected] (Richard Quadling)
Newsgroups php.db
Message-ID <[email protected]>
2009/11/11 Chris <[email protected]>:
> Andy Shellam (Mailing Lists) wrote:
>>
>> Hi,
>>
>>>
>>> If the databases are in the same mysql server, then you could qualify
>>> the table select with the database name and simply re-use the
>>> connection
>>>
>>> select db_name.table_name.field from db_name.table_name [where]
>>
>> No offence, but if I saw this in an application's source code, I'd run a
>> mile.
>
> Plus the assumption that they are on the same server and that the user
> you're connecting with has access to both databases..
>
> --
> Postgresql & php tutorials
> http://www.designmagick.com/
>
>
> --
> PHP Database Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

If it comes to that, if you are writing SQL code in PHP rather than
abstracting it or using stored procedures/views/etc. ...

Essentially the issue is 2 identical connections are not actually 2
identical connections.

They are 2 references to a single connection.

So, changing the DB via 1 resource changes the db for both resources.

NOTE: IDENTICAL. If the server or username is different, then that
results in a separate connection.

<?php
$conn1 = mysql_connect($server, $username, $password);
$conn2 = mysql_connect($server, $username, $password); // Is the same
connection as $conn1
mysql_select_db($db1, $conn1); // Both connection resources are now
looking at db1.
mysql_select_db($db2, $conn2); // Both connection resources are now
looing at db2.

_ONE_ solution is to use fully qualified names (you can use constants
if you don't like hard-coding the db name in the query).

Another option is to set the new_link flag on the mysql_connect() call.

That way you will have 2 separate connections.

<?php
$conn1 = mysql_connect($server, $username, $password, true);
$conn2 = mysql_connect($server, $username, $password, true); // Is NOT
the same connection as $conn1
mysql_select_db($db1, $conn1); // Points to db1 for connection1
mysql_select_db($db2, $conn2); // Points to db2 for connection2




-- 
-----
Richard Quadling
"Standing on the shoulders of some very clever giants!"
EE : http://www.experts-exchange.com/M_248814.html
Zend Certified Engineer : http://zend.com/zce.php?c=ZEND002498&r=213474731
ZOPA : http://uk.zopa.com/member/RQuadling
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.