gpt4 book ai didi

php - 类之间能否保持PDO连接?

转载 作者:可可西里 更新时间:2023-11-01 06:49:08 24 4
gpt4 key购买 nike

我正在尝试制作一个简单的查询库,并且我正在使用 PDO 进行数据库访问。

假设我有以下两个类:

class FirstClass {
var $dbh;

function __construct($host,$dbname,$user,$pw) {
$this->dbh = new PDO ("mysql:host=$host;dbname=$dbname",$user,$pw);
}

function use_second($foo) {
return new SecondClass ($foo,$this->dbh);
}
}

class SecondClass {
function __construct($foo, $dbh) {
$sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
$sth = $sth->execute(array('foo'=>$foo));
// do something with the query
}
}

这是在类之间使用相同 PDO 连接的正确方法吗? - 因为我似乎对此有一些问题,例如,如果我 var_dump 我从二等类的连接,我得到:

object(PDO)#2 (0) { }

这肯定是不对的?

此外,如果我运行一个选择查询,然后转储 $sth 变量,我只会得到:

bool(true)

这是因为我处理连接不正确吗? - 如果是这样,我如何才能在类之间正确使用相同的连接?

最佳答案

发生这种情况是因为您覆盖了 $sth,这是您的语句,但现在是一个 bool 值:

class SecondClass {
function __construct($foo, $dbh) {
// returns PDOStatement:
$sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
// returns boolean:
$sth = $sth->execute(array('foo'=>$foo));
// do something with the query
}
}

要更正它,只需不要覆盖 $sth,这样您就可以从中获取结果:

class SecondClass {
function __construct($foo, $dbh) {
// returns PDOStatement:
$sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
// returns boolean:
$success = $sth->execute(array('foo'=>$foo));
// do something with the query
if ($success) {
// do something with $sth->fetchAll() or $sth->fetch(), or anything
$all_the_results = $sth->fetchAll();
};
}
}

关于php - 类之间能否保持PDO连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9035691/

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