-1

我创建了一个 Mysql 连接数组并将其传递给连接方法,如下所示:

 $database->connect(array(ROOT_DB_HOST, 
        ROOT_DB_NAME, ROOT_DB_USERNAME, ROOT_DB_PASSWORD));

当我print_r()在 connect 方法中使用数组时,我得到了我的期望:

Array
(
    [0] => localhost
    [1] => dbname
    [2] => dbuser
    [3] => dbpass
)

但是,在 connect 方法中,我将数组值传递给 DSN 字符串,我收到了 0、1、2、3 上的未定义偏移量。这是 DSN 字符串:

$this->dbh = new PDO('mysql:host='. $connection[0] .';dbname=' . $connection[1],     $connection[2], $connection[3]);

所以我将值作为数组传递并将它们插入 PDO 构造函数并接收错误,我不知道发生了什么,有什么想法吗?

方法:

public function connect($connection) {
    try {
        $this->dbh = new PDO('mysql:host='. $connection[0] .';dbname=' .  $connection[1], $connection[2], $connection[3]);
        $this->dbh->setAttribute(PDO::ATTR_ERRMODE,  PDO::ERRMODE_EXCEPTION);
        $this->dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    } catch(PDOException $e) {
        throw new Exception($e->getMessage());
    }
}

错误:

注意:未定义的偏移量:第 16 行的 database.class.php 中的 0 注意:未定义的偏移量:第 16 行的 database.class.php 中的 1 注意:未定义的偏移量:第 16 行的 database.class.php 中的 2 注意:未定义的偏移量: 3 在第 16 行的 database.class.php 中

致命错误:在 database.class.php:20 中未捕获异常 'Exception' 并带有消息 'SQLSTATE[28000] [1045] Access denied for user 'apache'@'localhost' (using password: NO)' 堆栈跟踪:#0 sandboxx .php(16): Database->connect(Array) #1 {main} 在第 200 行的 database.class.php 中抛出

4

2 回答 2

-1

您在连接数据库句柄时遇到问题。如果您先创建
dsn,然后在处理程序中使用它。

$dsn = 'mysql:host='.$connection[0].';dbname='.$connection[1].'';
$dbh = new PDO($dsn, $connection[2], $connection[3]);
于 2013-05-12T18:43:24.443 回答
-2

What's the point in storing constants in array? Why not to use them already?
Also, you have quite strange way of handling exceptions.

public function connect($connection) {
    $opt = array(
        PDO::ATTR_ERRMODE          =>  PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES => false,
    );
    $dsn = 'mysql:host='. ROOT_DB_HOST .';dbname='.ROOT_DB_NAME; 
    $this->dbh = new PDO($dsn, ROOT_DB_USERNAME, ROOT_DB_PASSWORD, $opt);
}

Personally I don't understand why PDO has such inconsistent configuration, utilizing three different kinds of settings - DSN, parameters and options.
why can't you just feed PDO with array of settings - it's a mystery.

于 2013-05-12T18:50:39.173 回答