Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you connect to multiple MySQL databases on a single webpage?

Tags:

php

mysql

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.

I know how to connect to a single database using:

$dbh = mysql_connect($hostname, $username, $password) 
        or die("Unable to connect to MySQL");

However, can I just use multiple "mysql_connect" commands to open the other databases, and how would PHP know what database I want the information pulled from if I do have multiple databases connected.

like image 667
JoshFinnie Avatar asked Nov 08 '08 16:11

JoshFinnie


People also ask

Is it possible to connect to multiple databases simultaneously?

This can be done several times to connect to different databases, with the restriction that it will only allow one connection to the same database. If you try to use a database from multiple instances of the same application either on the same computer or on different computers you will receive an error message.

Can we connect to two database in a web application?

Yes. Give it a go. "Is it possible to connect multiple database with one application." Yes.

How do you communicate with multiple database in single application?

so, based on user login, the application should connect different database server. For Ex: if user "xxx" login with credential and belogs to "ABC" company and the database is "ABC", then ABC data need to display on the web page.

How do I access data from multiple MySQL databases?

It is useful to access data from multiple databases. There are two methods to connect multiple MySQL databases into a single webpage which are: $link = mysqli_connect ( “host_name”, “user_name”, “password”, “database_name” ); $link = new mysqli ( “host_name”, “user_name”, “password”, “database_name” );

How to send a query to multiple databases at once?

You don't actually need select_db. You can send a query to two databases at the same time. First, give a grant to DB1 to select from DB2 by GRANT select ON DB2.* TO DB1@localhost;. Then, FLUSH PRIVILEGES;. Finally, you are able to do 'multiple-database query' like SELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2 etc.

How do I switch between two databases in MySQL?

If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could: Keep one connection open and call mysql_select_db() to swap between as necessary. Specify the database name when you reference tables within your queries (e.g. SELECT * FROM database2.tablename).

What is the difference between MySQL_connect and mysqli_connect?

Instead of mysql_connect use mysqli_connect. mysqli is provide a functionality for connect multiple database at a time. $Db1 = new mysqli ($hostname,$username,$password,$db_name1); // this is connection 1 for DB 1 $Db2 = new mysqli ($hostname,$username,$password,$db_name2); // this is connection 2 for DB 2


10 Answers

Warning : mysql_xx functions are deprecated since php 5.5 and removed since php 7.0 (see http://php.net/manual/intro.mysql.php), use mysqli_xx functions or see the answer below from @Troelskn


You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for the '$new_link' (fourth) parameter, otherwise the same connection is reused. For example:

$dbh1 = mysql_connect($hostname, $username, $password); 
$dbh2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);

Then to query database 1 pass the first link identifier:

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

and for database 2 pass the second:

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

If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2) e.g.:

mysql_query('select * from tablename');

Other options

If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:

  • Keep one connection open and call mysql_select_db() to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database.
  • Specify the database name when you reference tables within your queries (e.g. SELECT * FROM database2.tablename). This is likely to be a pain to implement.

Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.

like image 140
Tom Haigh Avatar answered Nov 03 '22 01:11

Tom Haigh


I just made my life simple:

CREATE VIEW another_table AS SELECT * FROM another_database.another_table;

hope it is helpful... cheers...

like image 39
Ihsan Kusasi Avatar answered Nov 03 '22 02:11

Ihsan Kusasi


Instead of mysql_connect use mysqli_connect.

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

$Db1 = new mysqli($hostname,$username,$password,$db_name1); 
// this is connection 1 for DB 1

$Db2 = new mysqli($hostname,$username,$password,$db_name2); 
// this is connection 2 for DB 2
like image 35
kaushik Avatar answered Nov 03 '22 03:11

kaushik


If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.

You would connect through PDO, like this:

try {
  $db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
  echo 'Connection failed: ' . $ex->getMessage();
}

(Of course replace databasename, username and password above)

You can then query the database like this:

$result = $db->query("select * from tablename");
foreach ($result as $row) {
  echo $row['foo'] . "\n";
}

Or, if you have variables:

$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();

If you need multiple connections open at once, you can simply create multiple instances of PDO:

try {
  $db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
  $db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
  echo 'Connection failed: ' . $ex->getMessage();
}
like image 21
troelskn Avatar answered Nov 03 '22 01:11

troelskn


Unless you really need to have more than one instance of a PDO object in play, consider the following:

$con = new PDO('mysql:host=localhost', $username, $password, 
      array(PDO::ATTR_PERSISTENT => true));

Notice the absence of dbname= in the construction arguments.

When you connect to MySQL via a terminal or other tool, the database name is not needed off the bat. You can switch between databases by using the USE dbname statement via the PDO::exec() method.

$con->exec("USE someDatabase");
$con->exec("USE anotherDatabase");

Of course you may want to wrap this in a catch try statement.

like image 28
Michael Ratcliffe Avatar answered Nov 03 '22 01:11

Michael Ratcliffe


Try below code:

    $conn = mysql_connect("hostname","username","password");
    mysql_select_db("db1",$conn);
    mysql_select_db("db2",$conn);

    $query1 = "SELECT * FROM db1.table";
    $query2 = "SELECT * FROM db2.table";

You can fetch data of above query from both database as below

$rs = mysql_query($query1);
while($row = mysql_fetch_assoc($rs)) {
    $data1[] = $row;
}

$rs = mysql_query($query2);
while($row = mysql_fetch_assoc($rs)) {
    $data2[] = $row;
}

print_r($data1);
print_r($data2);
like image 38
Paks Avatar answered Nov 03 '22 01:11

Paks


$dbh1 = mysql_connect($hostname, $username, $password);  
$dbh2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $dbh1); 
mysql_select_db('database2',$dbh2); 

mysql_query('select * from tablename', $dbh1);
mysql_query('select * from tablename', $dbh2);

This is the most obvious solution that I use but just remember, if the username / password for both the database is exactly same in the same host, this solution will always be using the first connection. So don't be confused that this is not working in such case. What you need to do is, create 2 different users for the 2 databases and it will work.

like image 28
Lazy Fellow Avatar answered Nov 03 '22 02:11

Lazy Fellow


You might be able to use MySQLi syntax, which would allow you to handle it better.

Define the database connections, then whenever you want to query one of the database, specify the right connection.

E.g.:

$Db1 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 1st database connection 
$Db2 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 2nd database connection

Then to query them on the same page, use something like:

$query = $Db1->query("select * from tablename")
$query2 = $Db2->query("select * from tablename")
die("$Db1->error");

Changing to MySQLi in this way will help you.

like image 28
user3857891 Avatar answered Nov 03 '22 02:11

user3857891


You don't actually need select_db. You can send a query to two databases at the same time. First, give a grant to DB1 to select from DB2 by GRANT select ON DB2.* TO DB1@localhost;. Then, FLUSH PRIVILEGES;. Finally, you are able to do 'multiple-database query' like SELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2 etc. (Don't forget that you need 'root' access to use grant command)

like image 38
Nagibaba Avatar answered Nov 03 '22 03:11

Nagibaba


if you are using mysqli and have two db_connection file. like first one is

define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define('**DB1**','database_name1');

$connMitra = new mysqli(HOST, USER, PASS, **DB1**);

second one is

    define('HOST','localhost');
    define('USER','user');
    define('PASS','passs');
    define(**'DB2**','database_name1');

    $connMitra = new mysqli(HOST, USER, PASS, **DB2**);

SO just change the name of parameter pass in mysqli like DB1 and DB2. if you pass same parameter in mysqli suppose DB1 in both file then second database will no connect any more. So remember when you use two or more connection pass different parameter name in mysqli function

like image 42
Kamal Bunkar Avatar answered Nov 03 '22 03:11

Kamal Bunkar