问题
I am new to the class programming in php ,Here is my database class.
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();
}
}
I am extending this to core class to do some database operations.
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));
}
}
Now i am invoking getData function like this way.
$db=new Core();
$db->getData();
But i will get this
Fatal error: Call to a member function fetchAll() on boolean. What is the error in my code?please help me
回答1:
You need to return the $result
only in the run()
method:
public function run($sql)
{
$result=$this->_connection->prepare($sql);
$result->execute();
return $result;
}
Returning the $result->execute();
is returning true
because the execute()
succeeded. You need to return the current state of $result
.
See if that works.
来源:https://stackoverflow.com/questions/33007203/php-pdo-class-programmingfatal-error-call-to-a-member-function-fetchall-on-b