简体   繁体   中英

PDO can't access the database connection instance

I have a database wrapper, and a static method to get PDO connection instance. Howewer, I can't access it when I want to make a PDO query.

Here is part of DB class:

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;
}

And here my query:

    $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>';

    }

But I am getting this error when i run the query:

Fatal error: Call to undefined method DB::prepare()

What I am doing wrong? Any help?

But this works when i do this way

$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>';

 }

How is this possible?

You call prepare on object DB not on PDO, i suggest add getter to class DB:

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

and modify preparing query:

$db = DB::getInstance();
$statement = $db->getPDO()->prepare(...);
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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM