How do I select a MySQL database to use with PDO in PHP?

前端 未结 4 1541
独厮守ぢ
独厮守ぢ 2020-12-05 04:18

I want to select a MySQL database to use after a PHP PDO object has already been created. How do I do this?

// create PDO object and connect to MySQL
$dbh =         


        
4条回答
  •  暖寄归人
    2020-12-05 04:46

    As far as I know, you have to create a new object for each connection. You can always extend the PDO class with a method which connects to multiple databases. And then use it as you like:

    public function pickDatabase($db) {
      if($db == 'main') {
        return $this->db['main']; //instance of PDO object
      else
        return $this->db['secondary']; //another instance of PDO object
    }
    

    and use it like $yourclass->pickDatabase('main')->fetchAll('your stuff');

提交回复
热议问题