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

前端之家收集整理的这篇文章主要介绍了php – 可以在类之间维护PDO连接吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

假设我有以下两个类:

  1. class FirstClass {
  2. var $dbh;
  3. function __construct($host,$dbname,$user,$pw) {
  4. $this->dbh = new PDO ("MysqL:host=$host;dbname=$dbname",$pw);
  5. }
  6. function use_second($foo) {
  7. return new SecondClass ($foo,$this->dbh);
  8. }
  9. }
  10. class SecondClass {
  11. function __construct($foo,$dbh) {
  12. $sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
  13. $sth = $sth->execute(array('foo'=>$foo));
  14. // do something with the query
  15. }
  16. }

这是在类之间使用相同PDO连接的正确方法吗? – 因为我似乎遇到了一些问题,例如,如果我从第二个类中var_dump我的连接,我得到:

  1. object(PDO)#2 (0) { }

当然那不对?

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

  1. bool(true)

这是因为我错误地处理了连接吗? – 如果是这样,我怎样才能在类之间正确使用相同的连接?

最佳答案
发生这种情况,因为你覆盖$sth,这是你的语句,但现在是一个布尔值:

  1. class SecondClass {
  2. function __construct($foo,$dbh) {
  3. // returns PDOStatement:
  4. $sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
  5. // returns boolean:
  6. $sth = $sth->execute(array('foo'=>$foo));
  7. // do something with the query
  8. }
  9. }

要纠正它,只是不要覆盖$sth,这样你就可以从中获取结果:

  1. class SecondClass {
  2. function __construct($foo,$dbh) {
  3. // returns PDOStatement:
  4. $sth = $dbh->prepare('SELECT * FROM atable WHERE bar = :foo');
  5. // returns boolean:
  6. $success = $sth->execute(array('foo'=>$foo));
  7. // do something with the query
  8. if ($success) {
  9. // do something with $sth->fetchAll() or $sth->fetch(),or anything
  10. $all_the_results = $sth->fetchAll();
  11. };
  12. }
  13. }

猜你在找的MySQL相关文章