Reusing variables when working with PDO

I need to retrieve data from at least 3 databases, is there something wrong with reusing my PDO objects?

$dbh = new PDO('mysql:host=' . $host . ';dbname=' . $db_name, $user, $password);
$sth = $dbh->prepare($query1);

// do something

$dbh = new PDO('mysql:host=' . $host2 . ';dbname=' . $db_name2, $user2, $password2);
$sth = $dbh->prepare($query2);

//do something else

Sorry for editing, but here's another consideration. With each of them, I obviously have to check if the connection was successful, and throws an exception if this is not the case:

if (!$dbh) {
    $err=$dbh->errorInfo();
    throw new Exception('Could not connect: ' . $err[2]);
}

I do not think that there is a way to avoid this if I do not create all the connections at the same time and do not if (!dbh1|!dbh2) { ... }. Just think something else.

+3
source share
2 answers

$dbh new PDO(), pdo. PDO , . , , .

EDIT:

, , .

, , , , :

try catch, :

<?php
    try {
        $dbh = new PDO('mysql:host=localhost;dbname=databaseName', $userName, $password);

        foreach($dbh->query('SELECT * from TableName') as $row) {
            print_r($row);
        }

        $dbh = null;
    } catch (PDOException $ex) {
        print "Error!: " . $ex->getMessage() . "<br />";
        die();
    }
?>
+4

, ... . ( ), . () , , , ..

// connection to data warehouse
$dbh_dataWH = new PDO('mysql:host=' . $host . ';dbname=' . $db_name, $user, $password);
// connection to crm 
$dbh_crm = new PDO('mysql:host=' . $host2 . ';dbname=' . $db_name2, $user2, $password2);

, , - , .

+2

All Articles