0
我是php中的类编程新手,这里是我的数据库类。PHP PDO类编程:致命错误:调用布尔型的成员函数fetchAll()
class Database
{
private $_connection;
private static $_instance; //The single instance
private $_host = 'localhost';
private $_username = 'root';
private $_password = '';
private $_database = 'admission_portal';
//connect to database
public function connectDb()
{
try {
$this->_connection = new \PDO("mysql:host=$this->_host;dbname=$this->_database", $this->_username, $this->_password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
} catch (PDOException $e) {
echo $e->getMessage();
}
}
//run the query
public function run($sql)
{
$result=$this->_connection->prepare($sql);
return $result->execute();
}
}
我把它扩展到核心类来做一些数据库操作。
class Core extends Database
{
//get all the universities
public function getData()
{
Database::connectDb();
$sql = 'SELECT * FROM `adm_universities`';
$r=Database::run($sql);
print_r($r->fetchAll(PDO::FETCH_OBJ));
}
}
现在我正在像这样调用getData函数。
$db=new Core();
$db->getData();
,但我会得到这个
Fatal error: Call to a member function fetchAll() on boolean. What is the error in my code?please help me
关于如何在http://lampload.com/simple-database-connection-class-with-pdo.html – ahPo
下编写PDO连接类,您有一个很好的示例代码片段,您如何使用范围解析运算符调用connectDb (::)用于静态方法和变量? 我认为这部分是错误的 –