Reputation: 550
I'm new to PDO. I would like to know if there is anything similar to mysql_select_db in PDO, so that i can switch between different databases during runtime without the need for creating a new object.
Upvotes: 21
Views: 33052
Reputation: 174
you can make this :
$database1 = new PDO("mysql:host=localhost;dbname=db1;charset=utf8;",$username, $password);
$database2 = new PDO("mysql:host=localhost;dbname=db2;charset=utf8;",$username, $password);
simple 😀
Upvotes: 1
Reputation: 3500
There is not, you will need to create two PDO objects for the separate connections if you would like to use both at runtime.
Edit: Interesting point by @laz below (which I'm guessing is the cause of negative votes on my answer). I was thinking under the assumption that the databases were on separate servers tbh, in which case my answer stands.
Upvotes: 8
Reputation: 381
you don't even need to specify the database in every query, just use msyql syntax
USE db_name
and then write your requests
Upvotes: 6
Reputation: 131
You actually do not need to specify the database upon connection at all. As long as you specify the database in every query, as Laz stated, this will work:
$dbh = new PDO('mysql:host=127.0.0.1','USER','PASS');
$query = "SELECT * FROM database1.table1";
$query = "SELECT * FROM database2.table1";
Upvotes: 10
Reputation: 347
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.
Upvotes: 32
Reputation: 758
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());
Upvotes: 23