Hi wh335,
One way is to create two different database instances; one using database A's credentials and one using database B's Credentials.
So here is how to get both connections using PDO:
PHP Code:
<?php
class DBOne {
static $db ;
private $dbh ;
private function PDO_DBConnect(){
$db_type = 'mysql';
$db_name = 'testdb';
$user = 'db_user1' ; $password = '' ;
$host = 'localhost' ;
try {
$dsn = "$db_type:host=$host;dbname=$db_name";
$this->dbh = new PDO ( $dsn, $user, $password);
$this->dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch ( PDOException $e ) {
print "Error!: " . $e->getMessage () . "\n" ; die () ;
}
}
public static function getInstance ( ) {
if (! isset ( PDO_DBConnect::$db )) {
PDO_DBConnect::$db = new PDO_DBConnect ( ) ;
}
return PDO_DBConnect::$db->dbh;
}
}
class DBTWO {
static $db ;
private $dbh ;
private function PDO_DBConnect(){
$db_type = 'mysql';
$db_name = 'testdb2';
$user = 'db_user2' ; $password = '' ;
$host = 'localhost' ;
try {
$dsn = "$db_type:host=$host;dbname=$db_name";
$this->dbh = new PDO ( $dsn, $user, $password);
$this->dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch ( PDOException $e ) {
print "Error!: " . $e->getMessage () . "\n" ; die () ;
}
}
public static function getInstance ( ) {
if (! isset ( PDO_DBConnect::$db )) {
PDO_DBConnect::$db = new PDO_DBConnect ( ) ;
}
return PDO_DBConnect::$db->dbh;
}
}
You would set each connection by doing this:
PHP Code:
$o_DbA = DBOne::getInstance(); //Get Database A
$o_DbB = DBTwo::getInstance(); // Get Database B
$sql = 'SELECT...';
$stmt = $o_DBA->prepare($sql);
$stmt->execute();
$db_A_results = $stmt->fetch(PDO::FETCH_ASSOC);
foreach($db_A_results as $results){
foreach($result as $key => $value){
$stmt = $o_DbB ->prepare("INSERT INTO sometable (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $key);
$stmt->bindParam(':value', $value);
$stmt->execute();
}
}
Now you can use both connections to SELECT, UPDATE, INSERT AND DELETE data from the same application.
A different idea, hope this helps;
Steve
Bookmarks