PHP PDO class programming:Fatal error: Call to a member function fetchAll() on boolean

落花浮王杯 提交于 2020-01-11 13:14:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!