我正在尝试与PDO和Singleton类建立数据库连接,但我在从数据库中获取数据时遇到问题.
我一直在阅读这篇文章,但我仍然不确定如何从我的数据库文件中调用另一个文件中的Singelton类并打印出结果.我现在得到的错误是Fatal error: Call to undefined function query()在我的db.php文件中,这是我的数据库文件中的最后一个函数.但是我相信功能是定义的.
任何帮助表示赞赏!
这是我的数据库(db.php)连接文件:
<?php
class Database
{
private $_db;
static $_instance;
private function __construct() {
$this->_db = new PDO('mysql:host=localhost;dbname=mvcuser', 'root', '');
$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
private function __clone(){}
public static function getInstance() {
if (!(self::$_instance instanceof self)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function query($sql) {
return query($this->_db,$sql);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的index.php文件中的代码:
<?php
require_once 'model/db.php';
$db = Database::getInstance();
$db->query('SELECT * FROM users');
if ($result = $db->query($query)) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo $row;
}
}
Run Code Online (Sandbox Code Playgroud)
你的Database::query方法的定义没有意义.看起来你正在调用一些PHP函数query(它不存在),因此你得到了错误.
我想你可能想把方法的定义改为:
public function query($sql) {
return $this->_db->query($sql);
}
Run Code Online (Sandbox Code Playgroud)
更新:并在你的index.php
$db = Database::getInstance();
$statement = 'SELECT * FROM users';
if ($result = $db->query($statement)) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo $row;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这是追问有点老了,但任何人谁发现它从谷歌,如果你不希望创建为每一个PDO方法的包装方法,你可以使用这个你单身类中.
public function __call ( $method, $args ) {
if ( is_callable(array($this->_db, $method)) ) {
return call_user_func_array(array($this->_db, $method), $args);
}
else {
throw new BadMethodCallException('Undefined method Database::' . $method);
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以使用$db->query($statement)或任何其他PDO方法,而无需在单例类中定义它.