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);
}
}
$databaseis defined outside the class; and, similar to normal functions, you can't see the variable inside a class. Either pass it to the class as MrCode suggested or set it as global ( not recommended though ) as Rawkode suggested.