$con = new PDO($DSN,$user, $passwd);
But when you want to switch between multiple databases, what should you do? Now I give 3 methods for switching databases based on PDO objects.
All databases should be from or have same
1. server
2. db engine
3. user account
4. password.
Or you only use the third method.
Example:
Databases
first_db and second_db
tables:
f_name in first_db;
+------+-------+
| id | name |
+------+-------+
| 100 | China |
| 200 | japan |
| 300 | USA |
+------+-------+
s_name in second_db;
+------+-----------+
| id | name |
+------+-----------+
| 100 | Noda |
| 200 | Matsumoto |
| 300 | Okamoto |
+------+-----------+
initiate the pdo connection
$conn = new PDO('mysql:dbname=first_db;host=127.0.0.1;port=3306','user','passwd');
$sql = 'select * from s_name ';
$conn->query($sql);
Methods for switching first_db to second_db,
1. use 'use db';
$conn->exec('use second_db');
$sql = 'select * from s_name ';
$conn->query($sql);
2. use database name
$sql = 'select * from second_db.s_name ';
$conn->query($sql);
3. Create new connection
$conn = new PDO('mysql:dbname=second_db;host=127.0.0.1;port=3306','user','passwd');
$sql = 'select * from s_name ';
$conn->query($sql);
No comments:
Post a Comment