gpt4 book ai didi

php - 如何在 __construct() 中创建 PDO 连接?

转载 作者:行者123 更新时间:2023-11-29 06:21:02 25 4
gpt4 key购买 nike

我有一个包含三个方法的类。所有这些方法都需要数据库,然后我想在一切之前创建一个连接数据库的系统。像这样:

Class myclass
{
private $db;

public function __construct() {

$db = new PDO("mysql:host = hostname; dbname = database",username, password);
}

function one() {/* it needs to database and I will use it like this: */
$this->$db->prepare("select ...");
}
function two() {/* also it needs to database */}
function three() {/* also it needs to database */}
}

现在我想知道(首先)我所做的是一种标准方法吗?和(第二)我如何检查[如果连接断开(换句话说连接不存在)然后连接]?

最佳答案

要访问类属性,您必须使用 -> 语法:

Class myclass
{
private $db;

public function __construct() {

$this->db = new PDO("mysql:host = hostname; dbname = database",username, password);
}

function one() {/* it needs to database and I will use it like this: */
$this->db->prepare("select ...");
}
function two() {/* also it needs to database */}
function three() {/* also it needs to database */}
}

如果你想检测错误,启用错误信号

$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

并在使用数据库的代码周围使用try/catch:

function one() {
try {
$this->db->prepare(...);
} catch (PDOException $e) {
// handle error
}
}

关于php - 如何在 __construct() 中创建 PDO 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33258551/

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