包括到类的连接文件“;未定义的变量conn”;


Including connection file to a class "Undefined variable conn"

我有两个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;
    }

将文件包含在类之外是不起作用的。

您可以将$con变量作为参数传递,因为您也不能将文件包含在函数中。

所以请更改

public function fetchAllRows($table, $rowOrder, $direction)

public function fetchAllRows($table, $rowOrder, $direction,$con)

当您调用函数时,只需将连接链接作为函数调用中的一个参数传递即可。