0

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;

    }

}
4

1 に答える 1

3

PDO の場合、USE dbname直接実行しないでください。

PHPスクリプトの複数のインスタンスがあり、PDOがそれを認識せずにそれぞれが実行されると、何が起こっていると思いますかUSE dbname。これにより、全体が混乱します。

代わりに、PDO 接続文字列で dbname を指定する必要があります'mysql:host=localhost;dbname=testdb'。つまり、Model クラスを作成した後は、データベースを実際に切り替えることはできません。データベース名を事前に把握し、それをモデル コンストラクターで使用する必要があります。

詳しくはPDO ドキュメントを参照してください。

于 2013-02-18T09:30:33.750 に答える