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

标签 php mysql oop pdo

我正在尝试制作一个简单的查询库,并且我正在使用 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/

相关文章:

php - 如何从 PHP 中的字符串中提取 URL?

php - Instagram API 无法找到有关私有(private)文件的信息

java - 使用 Java JDBC 针对 MySQL 的 "count"查询的返回类型是什么?

php - 对象存储的创建方法

oop - 行为驱动开发是关于设计还是分析?

php 变量不起作用,但硬编码数字会起作用,为什么?

php - 如何修复 fatal error : Uncaught ArgumentCountError?

MySQL - 使用 Join 进行更新突然需要很长时间

java - 当存在可变类的引用时如何将不可变性设置为类

PHP - 如何用另一个短语替换一个短语?