I’m defining models that share a common database. However, I’m having trouble passing a PDO object via require_once(). I’m getting the following error:
Fatal error: Call to a member function prepare() on a non-object...
I’m guessing this is just a scope issue. I tried declaring $database as a global in both files but that didn’t seem to work. Any ideas?
common.php
$host = 'localhost';
$dbname = 'database';
$username = 'user';
$password = 'pass';
$database = new PDO("mysql:host=$host;dbname=$dbname", $username, $password, array(PDO::ATTR_PERSISTENT => true));
product.php
require_once('common.php');
class Product {
function fetch_from_category($category) {
$query = $database->prepare('SELECT * FROM product WHERE product.category = ?');
$query->execute($category);
return $query->fetchAll(PDO::FETCH_ASSOC);
}
}
It is indeed a scope issue,
$databaseis not defined insideProduct::fetch_from_category. You should pass it into the object when instantiating it:…