php-mvc: Uncaught Error: Call to a member function prepare() on null

Notice: Undefined property: Food::$database in C:\xampp\htdocs\mysite\models\food.php on line 32

$query = $this->database->prepare(“SELECT id, name, type, price, active FROM food”);

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 15 (7 by maintainers)

Most upvoted comments

Hi @kishevans - that error means the prepare method is being called on a variable that contains null. The variable is $db. This line is setting that value:

$db = static::getDB();

So the getDB method is returning null. Please check that method to make sure it’s returning a database instance (post it here if necessary)

Thanks Alot Dave

On Wed, Jan 25, 2023 at 8:03 PM Dave Hollingworth @.***> wrote:

@aashutosh2820 https://github.com/aashutosh2820 The “root” account doesn’t have access to the database with the password you’re using (blank it looks like). Try creating a new user or finding out the root password.

— Reply to this email directly, view it on GitHub https://github.com/daveh/php-mvc/issues/63#issuecomment-1403714730, or unsubscribe https://github.com/notifications/unsubscribe-auth/A5OUWL3DHRPQTGPJUYHGLJ3WUE2R7ANCNFSM4PY6XLKA . You are receiving this because you were mentioned.Message ID: @.***>

Thank you @daveh placing the return $db statement at the end of the function solved it.

@kishevans The return $db; line is in the wrong place - if you call the method more than once in the same request, it will return null - it needs to be the last line of the method:

protected static function getDB()
{
    ...

    return $db;
}