SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    The Jellophonic Autobrain CHeeSeBLiND's Avatar
    Join Date
    Jul 2001
    Location
    Bolton, England
    Posts
    584
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    connecting to 2 dbs at the same time

    how can i connect to 2 different mysql databases?
    hmm...

  2. #2

  3. #3
    Mlle. Ledoyen silver trophy seanf's Avatar
    Join Date
    Jan 2001
    Location
    UK
    Posts
    7,168
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hmm ... I moved this here thinking you meant how can you use tables from two different databases at the same time. If you just meant how can you connect to different database at different points in your script I'll move this back to the PHP forum

    BTW - welcome back

    Sean
    Harry Potter

    -- You lived inside my world so softly
    -- Protected only by the kindness of your nature

  4. #4
    SitePoint Zealot Egghead's Avatar
    Join Date
    Feb 2002
    Posts
    197
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Assuming you are using PHP...
    PHP Code:
    <?php
    // Set up one connection
    // Define database specific information
    define ("DB_HOST""localhost");
    define ("DB_USER""username");
    define ("DB_PASSWORD""password");
    define ("DB_NAME""database1");
     
    // define the database connection
    $db_connection mysql_connect(DB_HOSTDB_USERDB_PASSWORD);
     
    // now set up another connection...
    define ("DB_HOST2""localhost");
    define ("DB_USER2""username2");
    define ("DB_PASSWORD2""password2");
    define ("DB_NAME2""database2");
     
    $db_connection2 mysql_connect(DB_HOST2DB_USER2DB_PASSWORD2);
    ?>
    Now in your PHP script, just connect to the database using the relevant connection, do your query (mysql_query('SELECT ...)) and close the connection.
    PHP Code:
    <?php
    mysql_select_db
    (DB_NAME$db_connection) or die(mysql_error());
     
    // or if you want the other database, use this
    mysql_select_db(DB_NAME$db_connection2) or die(mysql_error());
     
    // Query here...
     
    // to close the connection
    mysql_close($db_connection);
    ?>
    You can put the definition bits of code into a seperate file, say "db.php", and then include it on any page or in any script that uses a database connection using the include() or require() function:
    include('db.php');


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •