可以在包含文件中找到数据库连接实例

问题描述 投票:0回答:0

我有两个页面

index.php
home.php
home.php
包含在index.php中并且数据库连接在
index.php
中处于活动状态(我已经检查过)。当我在
home.php
上课时,比如:

$Posts = new Posts($DBC);
$Tabs = new Tabs($Posts);
echo $Tabs->generateTabs();

我得到错误:警告:未定义的变量

$DBC
in

这是我的课程的样子:

class Posts {

    private $DBC;

    public function __construct($DBC) {
        $this->DBC = $DBC;
    } 
    public function getPosts($sql, $args = NULL){
    if (!$args)
    {
      return $this->DBC->query($sql);
    }
        $stmt = $this->DBC->prepare($sql);
        $stmt->execute($args);
        return $stmt;
    }
}

我的标签类是这样的:

class Tabs {
  
  private $dbal;

  public function __construct($dbal) {
   $this->dbal = $dbal;
  }
  public function generateTabs() {
    $tabs = $this->dbal->getPosts("SELECT * FROM tabs");
    $tabs = $tabs->fetchAll();
   ......
  }
}

所有必需的文件都包含在 index.php 中,如下所示:

require_once("db.php");
/* Verified connection is set */
if ($DBC->getAttribute(PDO::ATTR_CONNECTION_STATUS) === null) {
    echo 'Database connection is not active.';
} else {
    echo 'Database connection is active.';
}
base_url("common/functions.php");
base_url("classes/Posts.php");
base_url("common/tabs.php");

home.php
包含在
index.php

base_url("theme/home.php");

数据库连接:

$dsn = "mysql:host=$host;dbname=$database;port=$port;charset=$charset";
$options = [
  PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
  $DBC = new PDO($dsn, $username, $password, $options);
} catch (\PDOException $e) {
  throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

这是 base_url 函数:

function get_root_path() {
  return realpath(__DIR__);
}

function base_url($file_path) {
  $root_path = get_root_path();
  $full_path = $root_path . '/' . $file_path;
  require_once($full_path);
}
javascript php jquery mysqli pdo
© www.soinside.com 2019 - 2024. All rights reserved.