Would it be possible to have more than one databases to be connected in only one index.php, just like in a blog site where we will have different database for users information and another database for the blog information from the user?
5 Answers
$con=mysql_connect('host1', 'user1', 'password1');
mysql_select_db('db1',$con);
Pay attention to write function
1 Comment
mysql_select_db to indicating which connection resource should be used to select a database.Assuming you mean you want to connect to one database server, with multiple databases, just reference the database name with the table name. You "select" one database as your default, when you need to reference a table from another database, prepend the database name. For example, if your default database is the blog, you can query the user database like this:
SELECT * FROM users.user_table;
Comments
Maybe you should try using PDO.
Although it makes a little sense to split compact data (users + blog posts) into several databases, because you won't be able to use JOIN or FOREIGN KEY, but let's imagine you have situation where you need to sync your local user database with main blog database:
// Establish first connection
$dsn1 = 'mysql:dbname=testdb;host=127.0.0.1';
$user1 = 'dbuser';
$password1 = 'dbpass';
try {
$dbh1 = new PDO($dsn1, $user1, $password1);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$dsn2 = 'mysql:dbname=testdb;host=1.2.3.4';
$user2 = 'dbuser2';
$password2 = 'dbpass2';
try {
$dbh2 = new PDO($dsn2, $user2, $password2);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
foreach ($dbh1->query('SELECT ...') as $row) {
$dbh2->query( 'INSERT INTO...');
}