PDO无法访问数据库连接实例

时间:2014-02-21 15:06:11

标签: php mysql pdo

我有一个数据库包装器和一个静态方法来获取PDO连接实例。但是,当我想进行PDO查询时,我无法访问它。

以下是数据库类的一部分:

class DB {
private static $_instance = null;
private $_pdo,
        $_query,
        $_error = false,
        $_results,
        $_count =0;


private function __construct() {
    try {
        $this->_pdo = new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));

    } catch (PDOException $e) {
        die($e->getMessage());

    }
}

public static function getInstance() {
    if(!isset(self::$_instance)) {
        self::$_instance = new DB();

    }
    return self::$_instance;
}

我的查询在这里:

    $pdo = DB::getInstance();

    $statement = $pdo->prepare("select surname from staff_info where fname = :name");
    $statement->execute(array(':name' => Input::get('name')));
    $total = $statement->rowCount();

   while ($row = $statement->fetch(PDO::FETCH_ASSOC)) { 
            echo $row['surname'].'</br>';

    }

但是当我运行查询时,我收到此错误:

  

致命错误:调用未定义的方法DB :: prepare()

我做错了什么?有什么帮助吗?

但是这样做的时候我会这样做

$dsn = 'mysql:host=localhost;dbname=cois';
$user = 'root';
$password = '';
$pdo = new PDO($dsn, $user, $password);


$filmName = "omar";

$statement = $pdo->prepare("select surname from staff_info where fname = :name");
$statement->execute(array(':name' => $filmName));
$total = $statement->rowCount();

while ($row = $statement->fetch(PDO::FETCH_ASSOC)) { 
      echo $row['surname'].'</br>';

 }

这怎么可能?

2 个答案:

答案 0 :(得分:5)

你在对象DB上调用prepare不在PDO上,我建议将getter添加到类DB:

public function getPDO(){ 
  return $this->_pdo;
}

并修改准备查询:

$db = DB::getInstance();
$statement = $db->getPDO()->prepare(...);

答案 1 :(得分:0)

private function __construct() {
    try {
         self::$_instance = new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));

    } catch (PDOException $e) {
        die($e->getMessage());

    }
}
public static function getInstance() {
    if(!isset(self::$_instance)) {
         new DB();

    }
    return self::$_instance;
}