Multiple Databases using PDO

孤者浪人 提交于 2019-12-25 04:46:08

问题


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;

    }

}

回答1:


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.



来源:https://stackoverflow.com/questions/14932900/multiple-databases-using-pdo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!