加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程 > 正文

php – 可以在类之间维护PDO连接吗?

发布时间:2021-03-18 02:04:39 所属栏目:编程 来源:网络整理
导读:我正在尝试创建一个简单的查询库,我正在使用PDO进行数据库访问. 假设我有以下两个类: class FirstClass { var $dbh; function __construct($host,$dbname,$user,$pw) { $this-dbh = new PDO ("mysql:host=$host;dbname=$dbname",$pw); } function use_secon

我正在尝试创建一个简单的查询库,我正在使用PDO进行数据库访问.

假设我有以下两个类:

class FirstClass {
    var $dbh;

    function __construct($host,$dbname,$user,$pw) {
        $this->dbh = new PDO ("mysql:host=$host;dbname=$dbname",$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) { }

当然那不对?

另外,如果我运行一个select查询,然后转储$sth变量,我只得到:

bool(true)

这是因为我错误地处理了连接吗? – 如果是这样,我怎样才能在类之间正确使用相同的连接? 最佳答案 发生这种情况,因为你覆盖$sth,这是你的语句,但现在是一个布尔值:

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();
        };
    }
}

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读