How do you connect to multiple MySQL databases on a single webpage?

后端 未结 11 2350
青春惊慌失措
青春惊慌失措 2020-11-22 05:06

I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 05:35

    Unless you really need to have more than one instance of a PDO object in play, consider the following:

    $con = new PDO('mysql:host=localhost', $username, $password, 
          array(PDO::ATTR_PERSISTENT => true));
    

    Notice the absence of dbname= in the construction arguments.

    When you connect to MySQL via a terminal or other tool, the database name is not needed off the bat. You can switch between databases by using the USE dbname statement via the PDO::exec() method.

    $con->exec("USE someDatabase");
    $con->exec("USE anotherDatabase");
    

    Of course you may want to wrap this in a catch try statement.

提交回复
热议问题