我正在定义共享公共数据库的模型。但是,我无法通过require_once()
. 我收到以下错误:
Fatal error: Call to a member function prepare() on a non-object...
我猜这只是一个范围问题。我尝试在两个文件中都声明$database
为 a global
,但这似乎不起作用。有任何想法吗?
常见的.php
$host = 'localhost';
$dbname = 'database';
$username = 'user';
$password = 'pass';
$database = new PDO("mysql:host=$host;dbname=$dbname", $username, $password, array(PDO::ATTR_PERSISTENT => true));
产品.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);
}
}