2つのphpファイルがあり、そのうちの1つはクラスです。データベースに接続する
$conn
変数を持つファイルを含めようとしています。問題は、このエラーが発生することです。
Notice: Undefined variable: conn in /home/yuran/public_html/avec/DatabaseContent.php on line 20
Fatal error: Call to a member function prepare() on a non-object in /home/yuran/public_html/avec/DatabaseContent.php on line 20
これがコードです:
connection.php
<?php
require_once('constants.php');
try{
//Create a database connection
$conn = new PDO("mysql:host=".DB_SERVER.";"."dbname=".DB_NAME,DB_USER, DB_PASS);
} catch(PDOException $pe){
die("Could not connect to the database ".DB_NAME.": ".$pe->getMessage());
}
?>
DatabaseContent.php
<?php
include('inc/conn/connection.php');
class DatabaseContent{
public function fetchAllRows($table, $rowOrder, $direction){
$this->sql .= "ORDER BY :roworder :direction";
$q = $conn->prepare($this->sql);
$q->execute(array(':table'=>$table, 'roworder'=>$rowOrder, ':direction'=>$direction));
$q->setFetchMode(PDO::FETCH_ASSOC);
return $q;
}
クラス外のファイルを含めることはできません。
関数内にファイルを含めることもできないため、
$con
変数をパラメーターとして渡すことができます。
だからあなたを変える
public function fetchAllRows($table, $rowOrder, $direction)
に
public function fetchAllRows($table, $rowOrder, $direction,$con)
また、関数を呼び出すときは、接続リンクを関数呼び出しのパラメーターとして渡すだけです。