0

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 5

2
$con=mysql_connect('host1', 'user1', 'password1'); 
mysql_select_db('db1',$con); 

Pay attention to write function

Sign up to request clarification or add additional context in comments.

1 Comment

+1'd this one for using the second parameter of mysql_select_db to indicating which connection resource should be used to select a database.
1

Just use

mysqlconnect('host1', 'user1', 'password1'); 
mysql_select_db('db1'); 

to select diferent databases from the same server.

Comments

1

Although it is quite possible, it would make very little sense to split users and blog entries between separate databases.
If you are doing it for some reason, you better revise your architecture.

May be you are confusing a database and a table?

Comments

0

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

0

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...');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.