Search code examples
phpmysqlsqlprepared-statementfatal-error

"Fatal error: Call to a member function prepare() on a non-object.."


Following error occures:

Fatal error: Call to a member function prepare() on a non-object

The code:

class Guestbook {

    public $db;

    public function getEntries(){
        $result = false;
        $query = 'SELECT * FROM db ORDER BY id DESC'; 

        $stmt = $this->db->prepare($query); //error in this line (17)                               
        // ...
    }   
}       

Solution

  • You have this class:

    class Guestbook {
        public $db;
    

    You never give the $db property a value, so when you do

    $this->db->prepare($query);
    

    You're basically doing

    null->prepare($query);
    

    Give $db a value in the class constructor (or make sure it's passed into the class somehow, either way..) and you'll be fine.

    The

    $db = new mysqli('localhost', 'root', '', 'guestbook');
    

    In the database connection has no relation with the $db variable in the class unless you pass it into the class or make the database-initialization happen within the class.