【问题标题】:PHP PDO ConnectionPHP PDO 连接
【发布时间】:2011-07-23 14:57:50
【问题描述】:

我想在 PHP 中使用 PDO 为数据库连接创建一个连接类

这是我的代码:

<?php
class DatabaseConnection {

private $dbname     = "db_01";
private $host       = "localhost";
private $user       = "xxx";
private $password   = "xxxxxx";
private $port       = 5432;

private $DBH;

public function __construct() {
    try {
        $this->DBH  = new PDO("pgsql:host=$this->host;port=$this->port;dbname=$this->dbname;user=$this->user;password=$this->password");
    } catch(PDOException $e) {
        echo    $e->getMessage();  
    }

}
public function disconnect() {
    $this->DBH  = null; 
}
}
?>

对于 PDO 中的查询,我必须使用 $DBH->query('SELECT * from user');

但是如果我在其他类中使用我的连接类呢?

例子

<?php
include "DatabaseConnection.php";
class User {
    private $connection;

    public function getUser() {
        $this->connection = new DatabaseConnection();
        $STH = $this->connection->query('SELECT * from User');
    }
}
?>

但它不起作用。

任何机构可以帮助我?谢谢:)

更新

按照约拿的建议,

<?php

class DatabaseConnection extends PDO {

private $dbname     = "db_01";
private $host       = "localhost";
private $user       = "xxx";
private $password   = "xxxxxxxxx";
private $port       = 5432;

public function __construct() {
    try {
        parent::__construct("pgsql:host=$this->host;port=$this->port;dbname=$this->dbname;user=$this->user;password=$this->password");
    } catch(PDOException $e) {
        echo    $e->getMessage();  
    }

}
public function disconnect() {
    $this = null;   
}
}
?>

我在浏览器中收到消息“连接已重置”,怎么了?

【问题讨论】:

  • 您能否提供错误消息或说明究竟是什么失败了?我目前的猜测是,DatabaseConnection 类中没有名为 query 的方法。
  • @vstm :不,什么都没有出现,什么都没有。你以前有过 PDO 吗?
  • 如果没有显示任何内容,则最终没有错误,并且您的脚本不会产生任何输出。另一方面,PHP 可能会抑制错误消息。如果display_errorson 并且error_reporting 设置为E_ALL | E_STRICT,请检查您的php.ini。如果display_errors 已打开并且仍然没有输出,则应添加echo "hello world"; 以检查脚本是否正常运行。

标签: php postgresql pdo


【解决方案1】:

那行不通。您要么需要在 PDO 中创建一个调用 query 的方法:

class DatabaseConnection {
    // ...
    public function query($sql) {
        return $this->DBH->query($sql);
    }
    // ...
}

或扩展 PDO。

class DatabaseConnection extends PDO {
    // ...
}

更新: 另一方面,包装 PDO 类没有什么意义。为什么不直接创建 PDO 对象?

【讨论】:

  • 什么最好,创建一个查询方法或扩展它自己的 PDO ?谢谢
  • @Ahmad:扩展它可能会更容易。第二段代码是扩展它的一个例子;只需将您的其他方法放入其中即可。
  • 我修改了我的代码: public function __construct() { try { parent::__construct("pgsql:host=$this->host;port=$this->port;dbname=$this- >dbname;user=$this->user;password=$this->password"); } catch(PDOException $e) { echo $e->getMessage(); } } 公共函数断开() { $this = null;但我在浏览器中得到“连接已重置”
【解决方案2】:
class User {
  private $connection;

  public function __construct ($connection) {
    $this->connection = $connection;
  }

  public function getUser() {
    $STH = $this->connection->query('SELECT * from User');
  }
}

【讨论】:

  • 我通常使用这个的变体。你可以通过类型提示来改进它。
猜你喜欢
  • 2013-03-27
  • 2014-02-02
  • 2013-04-02
  • 2013-12-14
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
  • 2015-08-04
相关资源
最近更新 更多