Simultaneous MySQL DB Connections in PHP
I recently added a copy function to one of the web applications that I’ve developed. In addition to letting the user copy records to a new set of records in the same system, I decided to also allow them to copy to other instances of the system. My thought is that administrators can publish their configurations directly from a test environment to a production environment without needing me to generate a script and move data from system to system.
Having already completed the code to select the data, insert new records, and save those keys for future inserts, the most difficult part was connecting to two MySQL databases at once.
But in fact, the mysql_select_db() and mysql_query() functions take an optional second parameter to let you specify which database handle gets used for the query.
1 2 3 4 5 6 |
$dbh1 = mysql_connect($host, $user, $password); $dbh2 = mysql_connect($host, $user, $password); mysql_select_db('database1', $dbh1); mysql_select_db('database2', $dbh2); |
To query database 1, it’s as easy as
1 2 |
mysql_query('select field from table', $dbh1); |
and for database 2,
1 2 |
mysql_query('select field from table', $dbh2); |