13

Let's say user have two databases hosted on single host and I need to connect to both of them so that I can use any table anytime without adding connection code multiple times.

I have implemented this in CodeIgniter with adding authorization details of both databases in database.php file and to load required database with $this->load->database('dbname'); in script.

Now, for core PHP, we can do this like:

mysql_connect ('host','user','password','port','dbname'); // connection with one database.   

It was connected with my first database.

Now, I want to connect with second database:

1) I have not closed above connection and connected with second one with

mysql_connect ('host','user','password','port','dbname1');.

2) Would it be bad practice to do so ? Would it consume more objects ? Should we be required to close first one anyhow?

halfer
  • 19,824
  • 17
  • 99
  • 186
CodeWithCoffee
  • 1,896
  • 2
  • 14
  • 36
  • Please share what you have already tried. – Mithun Mar 17 '15 at 05:35
  • Edited question!! please check – CodeWithCoffee Mar 17 '15 at 05:41
  • 5
    Sidenote: Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). [This article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide. – Michael Doye Mar 17 '15 at 05:51
  • 1
    Duplicate of [How do you connect to multiple MySQL databases on a single webpage?](http://stackoverflow.com/q/274892/1446005) – RandomSeed Mar 20 '15 at 10:45
  • 1
    are they on the same instance and just different database names? – jbrahy Mar 20 '15 at 18:12
  • Its just different database name on same instance – CodeWithCoffee Mar 23 '15 at 07:06

14 Answers14

14

It is not neccessary to open 2 connection just to use tables from 2 databases on the same server. You just need to use the database.table notation. Doing that means that you can even join tables from different databases in the same query

SELECT t1.col1, t1.col2, t2.col2, t2.col2
FROM db1.table1 AS t1 JOIN db2.table1 AS t2 ON t1.col1 = t2.col3

So if you have connected to db1 initially you can use db2 tables and the same if you connected to db2 you can use db1 tables.

David Soussan
  • 2,698
  • 1
  • 16
  • 19
  • So you mean to say,in above case if you already connected to db1, you don't require to connect with db2 ? And it will automatically access table of db2 ? – CodeWithCoffee Mar 23 '15 at 13:07
  • 1
    Yes, if you use the database.table notation as I show in my example. Of course the user must have the neccessary permissions on both schemas. – David Soussan Mar 23 '15 at 13:09
  • @David Soussan, No. You need to realise that to get a database connection handle with which you execute your queries, you must specify the database name, whether you use mysqli extension or PDO. So, how can you have db1 and db2 referenced in one single connection handle ? You said 'of course the user must have the necessary permissions on both schemas', maybe you should show how to do such connection first, then we can learn. – Stephen Adelakun Mar 24 '15 at 09:51
  • @StephenAdelakun You are wrong. David is right. In MySQL you can reference all accessible tables throughout different schema's in the same connection and even the same query. This answer is the most relevant one. The schema you specify during the connection will be your selected (default) schema, meaning that queries that don't specify the schema will assume that one. But you can still say `schemaname.tablename` in the query to reference a table in another schema. – nl-x Mar 24 '15 at 10:30
  • @nl-x, I think I see the mix-up now. So you must have granted the user access to the two. OK, I missed that point. As a matter of fact, I never did that before. David was right in that case. Thanks nl-x for pointing this out. – Stephen Adelakun Mar 24 '15 at 12:47
7

Have you tried this?

$mysqli1 = new mysqli("example.com", "user", "password", "database1");

$mysqli2 = new mysqli("example.com", "user", "password", "database2");
Barcenal
  • 252
  • 3
  • 12
5

Why do you need two connections? The pros/advantages of two databases are actually primarily performance issues. But if you are on the same machine actually the only advantage you have, would be a cleaner separation. So it would be better to use one DB with two different prefixes for the table. So you seperate the diffent data by prefix and not by DB.

Dave
  • 263
  • 3
  • 12
4

You can do this by following object oriented approach

First of all create connection with two databases:

$Db1 = new mysqli('localhost','root','','database1'); // this is object of database 1
$Db2 = new mysqli('localhost','root','','database2'); // this is object of database 2

$query1 = 'select * from `table_name_of_database1`';  // Query to be run on DB1
$query2 = 'select * from `table_name_of_database2`';   // Query to be run on DB2

$result1 = $Db1->query($query1); // Executing query on database1 by using $Db1
$result2 = $Db2->query($query2); // Executing query on database2 by using $Db2

echo "<pre>";

/* Print result of $query1 */

if ($result1->num_rows > 0) {
    while($row = $result1->fetch_assoc()) {
        print_r($row);
    }
} else {
    echo "0 results";
}


/*========================================================*/


/* Print result of $query2 */

if ($result2->num_rows > 0) {
    while($row = $result2->fetch_assoc()) {
         print_r($row);
    }
} else {
    echo "0 results";
}

Conclusion: When you want to use database1 use $Db1 object and if you want to use database2 then use $DB2.

PHP Worm...
  • 4,109
  • 1
  • 25
  • 48
4

I don't think how to connect to 2 DBs simultaneously is the problem, as you have successfully done it ( or know how to do it ). I can gather that from your question. So I won't show how to do this. See other answers if you need to.

But to address your issues directly:

  1. Would it be bad practice to do so ? Generally, you should avoid 2 simultaneous DB connection handles as much as possible. If you only need to get data from one DB and use them to do something on the other, your best bet is to put the data from DB1 into appropriate PHP variables, close the connection; then make the second connection. That would be cheaper than keeping 2 DB connections open at the same time. However, if you are doing something like INSERT INTO db1.table SELECT FROM db2.table AND ALSO NEED TO COMMIT OR ROLLBACK depending on success or failure of some queries, then AFAIK, you need to keep both connections open until your processes are over. You see, there always trade-offs. So you decide based on the need of your application and bear the cost.

As a practical example of this scenario, I once worked on a project where I needed to SELECT a table1, INSERT INTO a table2, if the INSERT succeeds, I delete all the rows from table1, if the DELETE fails, I rollback the INSERT operation because the data cannot live in the two tables at the same time.

Of course, my own case involved only one DB, so no need of a second connection. But assuming the two tables were on different DBs, then that may be similar to your situation.

  1. Would it consume more objects ? No other objects other than the ones pointed out in 1 above, namely the DB connection handles according to your question.

  2. Should we compulsory require to close first one anyhow ? Once again, depending on your application needs.

Stephen Adelakun
  • 784
  • 2
  • 7
  • 24
3

Q: What cons are there to connect with other database without closing previous database?

A: When you connect to a database server physically are assigning resources to interact with you, if two databases are on the same server you would unnecessarily using resources that could be used to address other connections or other activities. Therefore you would be right close connections that do not need to continue using.

Q: Is this a appropriate practice to do so ? What is the best way to do so without opening this connection in every script multiple times ? I want this to get done in core php only as I have already know this in codeigniter.

One way SESSIONS, but you can't store database conections in sessions. Read in PHP.net this Warning: "Some types of data can not be serialized thus stored in sessions. It includes resource variables or objects with circular references (i.e. objects which passes a reference to itself to another object)." MySQL connections are one such kind of resource.

You have to reconnect on each page run.

This is not as bad as it sounds if you can rely on connection pooling via mysql_pconnect(). When connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection. The connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).

Reference:

http://php.net/manual/en/function.mysql-pconnect.php

http://www.php.net/manual/en/intro.session.php

Can't pass mysqli connection in session in php

Community
  • 1
  • 1
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
3

Instead of mysql_connect use mysqli_connect.

mysqli is provide a functionality for connect multiple database at a time.

kaushik
  • 903
  • 7
  • 16
2

1) Is it possible to connect with more than one database in one script ?

Yes we can create multiple MySQL link identifier in a same script.

2) It should be not like to close one connection with mysql_close and open new one,rather both connection should open at a time and user can use any table from any of the database ?

Use Persistent Database Connections like mysql_pconnect

3) If it is possible,what can be disadvantage of this ? Will there create two object and this will going to create issue ?

I don't think so it create any issue other than increasing some load on server.

Prabhat Kumar
  • 310
  • 1
  • 8
  • 1
    NEVER use persistent connections EVER. http://stackoverflow.com/questions/3332074/what-are-the-disadvantages-of-using-persistent-connection-in-pdo – David Soussan Mar 23 '15 at 12:57
  • @DavidSoussan Thanks for sharing that link. Didn't know that. But I don't agree with your conclusion to then NEVER EVER use it. The link warns for the caveats, but also gives solutions. – nl-x Mar 24 '15 at 10:45
  • Well after 30 years of using SQL and 15 years with MySQL I can say that I have never seen a situation where persistent connections were the answer. They just sound attractive to flat file programmers. Worry about this sort of thing when you hit a real performance bottleneck. I'll bet that when you do it will not be the database connection overhead that is the problem – David Soussan Mar 24 '15 at 11:50
2

You can use like this

$db1 = mysql_connect($hostname, $username, $password); 
$db2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('abc', $db1);
mysql_select_db('def', $db2);

For Database 1

mysql_query('select * from table1', $db1);

For Database 2

mysql_query('select * from table2', $db2);
Nikul
  • 1,025
  • 1
  • 13
  • 33
  • Thanks for response !! Is there any specific reason to add true for connection with $db2 ? – CodeWithCoffee Mar 17 '15 at 05:45
  • If you will not pass true for second database then it will make connection for only first database so it is neccessary to pass fourth parameter as true for second database – Nikul Mar 17 '15 at 05:53
  • @Nikul - would like to just correct you here where you have said that "it will make connection for only first database so it is neccessary to pass fourth parameter as true for second database". The significance behind adding the true is to not let the second connection override the first connection made. If you do not add true what it will do is it will over ride the db1 connection with db2. – Rakesh Lamp Stack Mar 21 '15 at 08:36
2

The best way to use multiple databases is to use PDO functions

EXAMPLE

// database cobfigurations
$config= array(
    // first database
    array(
        'type'=>'mysql',                    // DB type
        'host'=>'localhost',                // DB host
        'dbname'=>'database1',      // DB name
        'user'=>'root',                 // DB username
        'pass'=>'12345',                // DB password
    ),
    // second database
    array(
        'type'=>'mysql',                    // DB type
        'host'=>'localhost',                // DB host
        'dbname'=>'database2',      // DB name
        'user'=>'root',                 // DB username
        'pass'=>'987654',               // DB password
    ),
);
// database connections
$mysql=array();
foreach($config as $con)
{
    $con=(object)$con;
    $start= new PDO($con->type.':host='.$con->host.';dbname='.$con->dbname.'', $con->user, $con->pass, array(
            // pdo setup
            PDO::ATTR_PERSISTENT            => FALSE,
            PDO::ATTR_DEFAULT_FETCH_MODE    => PDO::FETCH_OBJ,
            PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES UTF8'
    ));

    if ($start && !empty($start) && !is_resource($start))
        $mysql[]=$start;    // connection is OK prepare objects
    else
        $mysql[]=false; // connection is NOT OK, return false
}

/**********************
 ****  HOW TO USE ****
**********************/ 

// fetch data from database 1
$data1 = $mysql[0]->query("SELECT id, title, text FROM content1")->fetchAll();
if(count($data1)>0)
{
    foreach($data1 as $i=>$result)
    {
        echo $result->id.' '.$result->title.' '.$result->text.'<br>'
    }
}

// fetch data from database 2
$data2 = $mysql[1]->query("SELECT id, title, text FROM content2")->fetchAll();
if(count($data2)>0)
{
    foreach($data2 as $i=>$result)
    {
        echo $result->id.' '.$result->title.' '.$result->text.'<br>'
    }
}

If you not use PDO before, please read this short tutorial:

http://www.mysqltutorial.org/php-querying-data-from-mysql-table/

Is practicly same like mysql and mysqli connections but is more advanced, fast and secure.

Read this documentations: http://php.net/manual/en/book.pdo.php

And you can add more then 2 databases

Ivijan Stefan Stipić
  • 6,249
  • 6
  • 45
  • 78
2

Use PDO supported by php 5 version instead mysql connect

Lerry
  • 146
  • 7
1

Here is a simple class that selects the required database automatically when needed.

class Database 
{
    private $host   = 'host';
    private $user   = 'root';
    private $pass   = 'pass';
    private $dbname = '';

    private $mysqli = null;

    function __construct() 
    {
        // dbname is not defined in constructor
        $this->mysqli = new mysqli( $this->host, $this->user, $this->pass );    
    }

    function __get( $dbname ) 
    {
        // if dbname is different, and select_db() is succesfull, save current dbname
        if ( $this->dbname !== $dbname && $this->mysqli->select_db( $dbname ) ) {
            $this->dbname = $dbname;
        }

        // return connection
        return $this->mysqli;
    }
}


// examples
$db = new Database();

$result = $db->db1->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );

$result = $db->db2->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );

$result = $db->{'dbname with spaces'}->query( "SELECT DATABASE()" );
print_r( $result->fetch_row() );
Danijel
  • 12,408
  • 5
  • 38
  • 54
1
$con1 = mysql_connect($hostname, $username, $password); 
$con2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $con1);
mysql_select_db('database2', $con2);

Then to query database 1 pass the first link identifier:

mysql_query('select * from tablename', $con1);

and for database 2 pass the second:

mysql_query('select * from tablename', $con2);
Apul Gupta
  • 3,044
  • 3
  • 22
  • 30
Mohit maru
  • 817
  • 8
  • 15
0

if mysql's user have permission to two database , you can join two table from two database etc:

SELECT database1.table.title title1,database2.table.title title2 
FROM database1.table
INNER JOIN database2.table 
ON (database1.table.id=database2.table.id)
Javad Khodadadi
  • 410
  • 1
  • 4
  • 13
  • Why the downvotes? Ok, the answer is quite short, but in fact it's one of the best ones here. – nl-x Mar 24 '15 at 13:19