[英]PDO can't access the database connection instance
I have a database wrapper, and a static method to get PDO connection instance. 我有一个数据库包装程序,还有一个获取PDO连接实例的静态方法。 Howewer, I can't access it when I want to make a PDO query.
Howewer,我想进行PDO查询时无法访问它。
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()
致命错误:调用未定义的方法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: 您在对象DB而不是PDO上调用prepare,我建议将getter添加到类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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.