PHP's mysql_connect Function Anomalie

Recently, when trying to make 2 similtanious connections to the same mysql server with different databases, I noticed that this is not strictly possible without a little tweak.

The following will not work as expected:

$con1 = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('db1', $con1);

$con2 = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('db2', $con2);

You would be left with one connection, $con2.  The reason seems to be that, when connecting subsequent times to the server with the same connections properties, the connection handle is reused.

To avoid this problem, vary the connection information. Example:

$con1 = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('db1', $con1);

$con2 = mysql_connect('localhost':3306, 'user', 'pass');
mysql_select_db('db2', $con2);

You can explicitly specify a port, or use and ip, a different host name, etc.

Hope this saves someone time.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.