4

Quick Tips: Connecting Multiple MySQL Databases On A Single Page

Monie on June 18th, 2010 in Tutorials
mysql

Learn how to connect multiple MySQL database on a single page.

The Scenario

I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases on a single PHP webpage.

The Solution

You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass the value “true” as the forth parameter, otherwise the same connection is reused. Here is a demonstration on connecting multiple MySQL databases on a single Page.

Database One

    // Database ONE Connection

    // Constant variable declaration
    $host = 'localhost';
    $user = 'database_user';
    $pass = 'password';
    $name = 'database_name';

    // 1. Create database connection
    $db1_connection = mysql_connect($host, $user, $pass) or die(mysql_error());

    // 2. Select database to use
    $db1 = mysql_select_db($qn_name, $db1_connection) or die(mysql_error());

Database Two

    // Database TWO Connection

    // 1. Create the second database connection
    // Passing the "true" value in the forth parameter here
    $db2_connection = mysql_connect($host, $user, $pass, true) or die(mysql_error());

    // 2. Select database to use
    $db2 = mysql_select_db($name, $db2_connection) or die(mysql_error());

Problem solved! Happy coding…

4 Responses so far.

  1. WP Themes says:

    Nice post and this fill someone in on helped me alot in my college assignement. Say thank you you as your information.

  2. Monie says:

    Not sure if this is the best way of doing it. Share with me if you have a different method?

  3. dean says:

    Can you explain more on the true value? why do you need that? why can’t you just the same syntax (with increment) again?

  4. Monie says:

    From the PHP MYSQL reference, the syntax is as follows:

    mysql_connect(server,user,pwd,newlink,clientflag)

    The “newlink” refer to as:

    Optional. If a second call is made to mysql_connect() with the same arguments, no new connection will be established; instead, the identifier of the already opened connection will be returned

    Link: http://www.w3schools.com/PHP/func_mysql_connect.asp

Leave a Reply