Forum Moderators: coopster

Message Too Old, No Replies

Connecting to Two Databases Simultaneously

         

HoboTraveler

7:14 am on Jan 17, 2007 (gmt 0)

10+ Year Member



Hello,

Below is the connection info for connecting to two databases simultaneously. When querying the first database, the SQL Query does not connect since it defaults to the second DB.

Error Message:
Invalid query: Table 'db02.table01' doesn't exist

Am I missing something..?

TIA

// DB connection info
<?php

// First database
$db_one = mysql_connect("localhost","root","");
mysql_select_db("db01", $db_one);

// Second database
$db_two = mysql_connect("localhost","root","");
mysql_select_db("db02", $db_two);

?>

<?php

// This query does not work

$SqlInsertQuery =
("
INSERT INTO
table01
(
`dateInserted`
)
VALUES
(
NOW()
)
");

$SqlInsertResult = mysql_query($SqlInsertQuery, $db_one);

// Check result. This shows the Error
if (!$SqlInsertResult)
{
$SqlInsertMessage = 'Invalid query: ' . mysql_error() . "\n";
die($SqlInsertMessage);
}
?>

omoutop

7:26 am on Jan 17, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



General guidelines...

- in your queries use the {database}.{table}.{field} syntax if you are going to connect to multi databases
- i haven't figure a way to connect to two different servers, but you can connect to two databases on the same server
- take care as the two users (username of the databases) to have enough access to both of the databses (GRANT/REVOKE privilages... more info here [dev.mysql.com].

I know this may sound a little complicated, but really it is not

HoboTraveler

8:01 am on Jan 17, 2007 (gmt 0)

10+ Year Member



I was including the connection info through an includes file.

I put the connection info into the same file as the queries and it works Ok.

Any reason on why the includes file did not work? I did specify the resource link in the queries.

TIA