Jump to content

Simple SQL connecting to 2 databases at same time


johnsmith153

Recommended Posts

This is what I need to do (connect to two databases at same time)

 

$con1 = mysql_connect("server", "user", "pass");
if (!$con1)
{
echo "Could not connect to db 1: ". mysql_error();
exit;
}

//connect to db 2
$con2 = mysql_connect("server", "user", "pass");
if (!$con2)
{
echo "Could not connect to db 2: ". mysql_error();
exit;
}


//select db 1
mysql_select_db("dbase-name", $con1);

 

The problem is the above will not work - it doesn't select the first connection again - as though it has been lost.

 

However if I check if($con1) it DOES exist.

 

If I tried to perform queries on connection 2 - this would work.

Are the databases on the same server. You dont have to open 2 connections if so, you can prepend the table name with the database name:

mysql_query("SELECT * FROM db1.tablename ",$conn);
mysql_query("SELECT * FROM db2.tablename ",$conn);

Just dont use mysql_select_db()

by very its nature mysql_connect uses only one connection at a time to save resources  , try to close the first connection b4 using another or use

 

$conn1 = new mysqli($host,$username,$password,$databasename);

 

$result = $conn->query('select.....');

 

$conn2 = new mysqli($host2,$username2,$password2,$databasename2);

$result2 = $conn2->query('select.....');

 

for this make sure mysqli extension is loaded ....

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.