Switch between multiple database in PDO

I know that I am a couple of months late but you should be able to switch between databases from within your query.

examples:

$sql = "SELECT * FROM dbname.tablename";

$sql = "SELECT * FROM anotherdbname.anothertablename"

So even if your original $pdo object was used 'blahblah' as the dbname, you should still be okay based on the select examples I provided.


It looks like PDO does not have database switching because not every database engine supports it.

AFAIK PostgreSQL does not have database switching, but offer schemas and u can switch between those.

However if you're using mysql check if this works for you:

$pdo = new PDO('mysql:dbname=db1;host=127.0.0.1','user','pass');

$sql = 'select count(*) from table_name';

$res = $pdo->query($sql);
print_r($res->fetchAll());

$pdo->exec('USE db2');

$res = $pdo->query($sql);
print_r($res->fetchAll());

Tags:

Php