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)
Hi @kishevans - that error means the
preparemethod is being called on a variable that contains null. The variable is$db. This line is setting that value:$db = static::getDB();
So the
getDBmethod 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:
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: