2

我的情况:文件夹结构是/resources/website/inc/(/resources/是存储配置的地方,/website/包含index.php和/inc/

我在资源文件夹中的 config.php / 中定义了数据库连接的常量。

   define ( 'DB_HOST', 'localhost' );
   define ( 'DB_USER', 'my_username' );
   define ( 'DB_PASSWORD', 'my_password' );
   define ( 'DB_NAME', 'my_database' );

在 index.php 中访问数据库并显示数据。

我得出的结论是,它试图将 config.php 中定义的常量与 index.php 中的连接语句一起使用,但常量没有通过。

这是我的连接语句:

$connect = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or 
                         die("MySQL Error: " . mysql_error());
$db = mysql_select_db(DB_NAME) or die("MySQL Error: " . mysql_error());

当我将这两个部分添加到 config.php 中时,它可以完全正常工作,但是我想在各个区域进行连接和关闭连接,我不想再次定义变量

4

1 回答 1

5

您需要在可以通过 Web 服务器访问的每个其他文件中要求(包含)配置文件。

仅此而已:

config.php

define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'my_username' );
define ( 'DB_PASSWORD', 'my_password' );
define ( 'DB_NAME', 'my_database' );

public/index.php

require_once __DIR__ . '/../config.php';
// The rest of you code here

public/contact.php

require_once __DIR__ . '/../config.php';
// The rest of you code here
于 2012-05-03T01:34:57.857 回答