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

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

发布时间:2021-03-22 16:51:00 所属栏目:编程 来源:网络整理
导读:我正在实行建设一个简朴的查询库,我正在行使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();
        };
    }
}

(编辑:湖南网)

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

    热点阅读