gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:35:58 25 4
gpt4 key购买 nike

嗨,我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com