Connecting to multiple databases with PDO.

This is a short tutorial on how to connect to multiple MySQL databases in the same script using the PDO object.

With the older mysql_ extension, you could connect to MySQL and change between databases like so:

<?php

//Connect to MySQL.
$conn = mysql_connect('localhost', 'root', '');

//Select database one.
mysql_select_db('database_one', $conn);

//Query database one.

//Select database two.
mysql_select_db('database_two', $conn);

//Query database two.

As you can see, the same MySQL connection could beĀ used throughout the script. You’d simply switch the database by using the function mysql_select_db.

However, things work a bit differently with the PDO object:

<?php

//Connect to MySQL and select database one.
$databaseOne = new PDO('mysql:host=localhost;dbname=database_one', 'root', '');

//Query database one using $databaseOne.

//Connect to MySQL and select database two.
$databaseTwo = new PDO('mysql:host=localhost;dbname=database_two', 'root', '');

//Query database two using $databaseTwo.

With the PDO object, both the connection and the selected database are contained in the object. This is because the database is selected via the DSN string, which is passed in via the constructor!