Learn how to connect multiple MySQL database on a single page.
Learn how to connect multiple MySQL database on a single page.
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.
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 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 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…
Nice post and this fill someone in on helped me alot in my college assignement. Say thank you you as your information.
Not sure if this is the best way of doing it. Share with me if you have a different method?
Can you explain more on the true value? why do you need that? why can’t you just the same syntax (with increment) again?
From the PHP MYSQL reference, the syntax is as follows:
The “newlink” refer to as:
Link: http://www.w3schools.com/PHP/func_mysql_connect.asp