php - 为什么我的 PDO 对象返回对象(PDO)[2]

标签 php mysql pdo

嗨,我正在使用 PDO 为 mysql 开发一个基本的数据库连接类,但是当我 var dump 返回结果时,它告诉我我有 2 个对象:object(PDO)[2]。不应该只有一个吗?

这是迄今为止我的代码:

class DBConnection
{
    // Settings (DSN)
    protected $driver, $host, $name, $charset;

    // Credentials
    protected $user, $pass;

    // PDO Connection
    protected $connection;

    public function __construct() {
        require_once( 'database.config.php' );

        // Settings (DSN)
        $this->driver   = DB_DRIVER;
        $this->host     = DB_HOST;
        $this->name     = DB_NAME;
        $this->charset  = DB_CHARSET;

        // Credentials
        $this->user     = DB_USER;
        $this->pass     = DB_PASS;

        // Initialise Connection
        var_dump($this->getConnection());
    }

    private function getConnection() {
        // Check if connection is already established
        if ( $this->connection == NULL ) {
            $dsn = "$this->driver:host=$this->host;dbname=$this->name;charset=$this->charset";
            try {
                $this->connection = new PDO($dsn,$this->user, $this->pass);
                $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch ( PDOException $error ) {
                echo 'Connection failed: ' . $error->getMessage();
            }
        }
        return $this->connection;
    }
}

$new = new DBConnection();

配置文件:

define('DB_DRIVER', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'root');
define('DB_PASS', '');

最佳答案

    private function getConnection() {
    // Check if connection is already established
    if ( $this->connection == NULL ) {
        $dsn = "$this->driver:host=$this->host;dbname=$this->name;charset=$this->charset";
        try {
            $this->connection = new PDO($dsn,$this->user, $this->pass);
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            // This line is to remove associate array, then you will get only one object in result set
            $this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 
        } catch ( PDOException $error ) {
            echo 'Connection failed: ' . $error->getMessage();
        }
    }
    return $this->connection;
}

关于php - 为什么我的 PDO 对象返回对象(PDO)[2],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50286559/

相关文章:

ios - 哪些数据类型与 Core Data/SQL 一起使用以最大限度地减少转换

php - 自动增量主键重复输入错误?

mysql - Google Cloud SQL 是否支持 MySQL 的 ON CASCADE DELETE 功能?

javascript - 获取 iframe 内容的宽高

php - 如何使用 PHP 从 MySQL 数据库中读取图像?

php - 从 2 个不同的表中选择值并在具有相同 ID 的一行中打印值

mysql - 使用 Sum 函数连接多个表的 SQL 查询

mysql - 如何正确使用 sum (case ... when ... then ...) ?

php - 无法运行查询 : SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

php如何找到用户来自的位置?