Thursday, January 14, 2010

MySQL and mysql_select_db

I was convinced that mysql_select_db() was not working today. I wanted to simultaneously connect to two different databases. However, when I called the mysql_select_db function, it seemed that both connections were changing to the database I specified. I couldn't get one link to stay on the original database while I changed the second link to a new database.

After a little digging around I found a helpful user comment about using mysql_connect. The fourth parameter of this function is "new_link" and if you want to simultaneously have two connections open and both connections use the same credentials, you must set this parameter to TRUE. If you don't, it sees that the credentials are the same and will reuse the same resource link, even if you set a different variable.

So, this:

<?PHP
$conn1 = mysql_connect(HOST, USER, PASS);
mysql_select_db(TABLE_1, $conn1);
$conn2 = mysql_connect(HOST, USER, PASS);
mysql_select_db(TABLE_2, $conn2);

turned into this:

<?PHP
$conn1 = mysql_connect(HOST, USER, PASS, true);
mysql_select_db(TABLE_1, $conn1);
$conn2 = mysql_connect(HOST, USER, PASS, true));
mysql_select_db(TABLE_2, $conn2);

And tada, I could simultaneously connect to two (or more) databases.

No comments: