Page 1 of 1

How to switch between databases

Posted: Wed Jul 09, 2003 4:16 pm
by php_wiz_kid
Here's my problem. At the beginning of a page I connect to the server and select a MySQL database. Now towards the end of the script I need to get information from another database. Should I close the connection to the server from the first database, and open a new one and then select the other database? I tryed using

Code: Select all

mysql_select_db()
[/color] and just select the other database but that didn't work. Thanks. Sorry if it's confusing.

Posted: Wed Jul 09, 2003 4:52 pm
by Duke of PHP
I've never done it.. Yet.. But I would try this:

$db = mysql_select_db("DB_NAME");

Okay, you've established that database.. Now, if I wanted to escape from that one and go into another one, I would do:
mysql_close($db);

And then do the $db = mysql_select_db("DBNAME");

Get it? You have to close one before going into another.

Posted: Wed Jul 09, 2003 4:54 pm
by php_wiz_kid
Ok, I'll try that.

Posted: Wed Jul 09, 2003 5:00 pm
by php_wiz_kid
I get this error:
Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in C:\Program Files\Apache Group\Apache\htdocs\user\edit-profile.php on line 221

Posted: Wed Jul 09, 2003 5:04 pm
by php_wiz_kid
I got it, thanks everyone.

Posted: Thu Jul 10, 2003 5:41 am
by ik
Yeah, that right. But actually mySQL SQL syntax allows one to get query from any database without explicit switching: select *from db.table

Posted: Thu Jul 10, 2003 11:58 am
by php_wiz_kid
What I ended up doing is creating a function that used the mysql_connect() and mysql_select_db() functions. When I needed to connect to a new database I just called my function, passed the database to the function, and I didn't have to bother with closing the server connection to the database. It looked like this:

Code: Select all

їphp]
<?php
  function db_connect($db, $host = 'localhost', $user = '****', $pass = '****') &#123;
        $mysql_connect = mysql_connect($host, $user, $pass) or die("Error connecting to server");

        $mysql_select_db = mysql_select_db($db) or die("Error connecting to database");
  &#125;
?>&#1111;/php]
Then I'd just call db_connect('db_name');

I don't know if this is the best way of doing it, but it works.