views:

4959

answers:

7

I am trying to connect to 2 databases on the same instance of MySQL from 1 PHP script.

At the moment the only way I've figured out is to connect to both databases with a different user for each.

I am using this in a migration script where I am grabbing data from the original database and inserting it into the new one, so I am looping through large lists of results.

Connecting to 1 database and then trying to initiate a second connection with the same user just changes the current database to the new one.

Any other ideas?

+11  A: 

You'll need to pass a boolean true as the optional fourth argument to mysql_connect(). See PHP's mysql_connect() documentation for more info.

Lucas Oman
+1  A: 

I would suggest using two connection handlers

   $old = mysql_connect('old.database.com', 'user', 'pass);
   mysql_select_db('old_db', $old);


   $new = mysql_connect('new.database.com','user','pass);
   mysql_select_db('new_db', $new)

   // run select query on $old
   // run matching insert query on $new
The.Anti.9
That only works if both databases are on different servers.
Stefan Gehrig
+3  A: 

Lucas is correct. I assume that both the databases are hosted on the same host.

Alternatively, you can create only 1 db connection and keep swapping the databases as required. Here is pseudo code.

$db_conn = connect_db(host, user, pwd);
mysql_select_db('existing_db', $db_conn);
 -- do selects and scrub data --
mysql_select_db('new_db', $db_conn);
-- insert the required data --
Gaurav
+7  A: 

If your database user has access to both databases and they are on the same server, you can use one connection and just specify the database you want to work with before the table name. Example:

SELECT column
FROM database.table

Depending on what you need to do, you might be able to do an INSERT INTO and save a bunch of processing time.

INSERT INTO database1.table (column)
SELECT database2.table.column
FROM database2.table
Joe Lencioni
+1  A: 

If it's an option, use PDO: you can have as many database connections open as you like.

Plus, assuming your executing the same queries over and over, you can use prepared statements.

Gary Richardson
A: 

If you use 2 connection handlers, you definitely want to make sure you close both connections after using them. - Arunabh Das

Arunabh Das
But PHP will disconnect from the database when the script terminates http://php.net/manual/en/function.mysql-close.php
Darryl Hein
A: 

I want to connect to a remote datbase ,

In that case, how I will swap between two databases, one on localserver and other on remote server ..

Regards,

Zeetarian
You should post this as a question, not an answer to another question, but you'll need to do the same thing as this question and just store the 2 connections in 2 variables.
Darryl Hein