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 (::)用於靜態方法和變量? 我認爲這部分是錯誤的 –