How to switch between databases

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
php_wiz_kid
Forum Contributor
Posts: 181
Joined: Tue Jun 24, 2003 7:33 pm

How to switch between databases

Post 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.
Duke of PHP
Forum Newbie
Posts: 5
Joined: Mon Apr 21, 2003 2:20 pm

Post 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.
php_wiz_kid
Forum Contributor
Posts: 181
Joined: Tue Jun 24, 2003 7:33 pm

Post by php_wiz_kid »

Ok, I'll try that.
php_wiz_kid
Forum Contributor
Posts: 181
Joined: Tue Jun 24, 2003 7:33 pm

Post 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
php_wiz_kid
Forum Contributor
Posts: 181
Joined: Tue Jun 24, 2003 7:33 pm

Post by php_wiz_kid »

I got it, thanks everyone.
ik
Forum Commoner
Posts: 34
Joined: Thu Jul 10, 2003 5:33 am
Location: Lancs Uni, UK
Contact:

Post 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
php_wiz_kid
Forum Contributor
Posts: 181
Joined: Tue Jun 24, 2003 7:33 pm

Post 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.
Post Reply