我有两个php文件,其中一个是类。我试图包含具有连接到数据库的$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;
}
答案 0 :(得分:0)
在课堂外包含该文件将无效。
您可以将public function up()
{
Schema::create('image_post', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('image_id')->unsigned()->index();
$table->integer('post_id')->unsigned()->index();
$table->timestamps();
});
Schema::table('image_post', function($table) {
$table->foreign('image_id')->references('id')->on('image')->onDelete('cascade');
$table->foreign('post_id')->references('id')->on('post')->onDelete('cascade');
});
}
变量作为参数传递,因为您也无法在函数中包含该文件。
所以改变你的
$con
到
public function fetchAllRows($table, $rowOrder, $direction)
当您调用该函数时,只需将连接链接作为函数调用中的参数传递。