Q:

Multiple Databases using PDO

I'm pretty new to using PDO and I would like to set it up so I can have multiple databases as and when I need them. So I've created a function that allows you to pass a database name to be used as and when.
It does work to a certain extent, as in it selects the database you pass in but even if the database is omitted or incorrect it still allows you to select tables and rows from a database which seems to be selected at random based on the MySQL user.
This isn't a major issue I suppose but I would like to get it to where it won't select any data unless a database has been passed to through my function.
My code is below and I would appreciate your thoughts on how I may better approach this. Thanks.
index.php
require 'app/cream.php';

try {

    $db = new Cream_Model();
    $db = $db->selectDb( 'cream' );

    $data = $db->query('SELECT * FROM users');
    foreach( $data as $row ) {
        print_r( $row );
    }

} catch( PDOException $e ) {

    echo 'An error has occurrred: ' . $e->getMessage() . '<br />';

}

Model.php
class Model {

    public $connection;

    public function connect() {

        try {

            $connection = new PDO( DB_DSN . ':' . DB_HOST, DB_USERNAME, DB_PASSWORD, array( PDO::ATTR_PERSISTENT => true ) );
            $connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $connection->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC );

        } catch( PDOException $e ) {

            echo 'An error has occurred: ' . $e->getMessage() . '<br />';
            die();

        }

        return $connection;

    }

}

Cream_Model.php
class Cream_Model extends Model {

    public $conn;

    public function selectDb( $db ) {

        try {

            $conn = $this->connect();
            $conn->exec( "USE $db" );

        } catch( PDOException $e ) {

            echo 'An error has occurred: ' . $e->getMessage() . '<br />';

        }

        return $conn;

    }

}

A:

For PDO, you should NOT exec USE dbname directly.
I think what is happening that you have multiple instances of PHP script, and when each one executes USE dbname without PDO being aware of it happening, and this causes whole mess.
Instead, you should specify dbname in your PDO connection string like 'mysql:host=localhost;dbname=testdb'. That means you cannot really switch between databases after creating your Model class. You should know your database name upfront and use it in Model constructor.
Read more in PDO documentation.

