connect in 2 banks with PDO

1

Hello, I connect to a bank, how would I connect with another, who has the same login and password inside the same server? follows my function:

function conectaBanco() {

    $hostname='dbprovider.rede.local';
    $username='root';
    $password='8asd331221!';

    try {
        $dbh = new PDO("mysql:host=$hostname;dbname=Provider",$username,$password,
            array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        return $dbh;
    }

    catch(PDOException $e) {
        echo $e->getMessage();
    }
}

In case like I do here to connect with the other bank, example I want to put

$dbh2 = new PDO("mysql:host=$hostname;dbname=Provider2",$username,$password,

But it did not work !!! Can someone help? the error is Uncaught Error: Call to a member function query () on null line 48 and in that line has

$dbh = conectaBanco();
    
asked by anonymous 14.08.2018 / 13:43

1 answer

2

A basic example of your question:

function conectaBanco($nomeBD) {

    switch ($nomeBD) {
        case 'BD1':
        $hostname='192.168.0.1';
        $dbname='banco1';
        $username='root';
        $password='xx1!';
        break;

        case 'BD2':
        $hostname='192.168.0.1';
        $dbname='banco2';
        $username='root';
        $password='xx1!';
        break;

        case 'BD3':
        $hostname='192.168.0.100';
        $dbname='banco3';
        $username='root';
        $password='yy2!';
        break;

        default:
        $hostname='dbprovider.rede.local';
        $dbname='bd_padrao';
        $username='root';
        $password='zz3!';
        break;
    }

    try {
        $dbh = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password,
            array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        return $dbh;
    }

    catch(PDOException $e) {
        echo $e->getMessage();
    }
}

Using the function:

$obj = new ClasseConexao;
$obj -> conectaBanco('BD2');
    
14.08.2018 / 14:19