为mysql连接定义

Ren*_*nai 2 html php mysql

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

我已在config.php /资源文件夹中为db连接定义了常量.

   define ( 'DB_HOST', 'localhost' );
   define ( 'DB_USER', 'my_username' );
   define ( 'DB_PASSWORD', 'my_password' );
   define ( 'DB_NAME', 'my_database' );
Run Code Online (Sandbox Code Playgroud)

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

我得出的结论是,它试图在config.php中使用定义的常量和index.php中的connect语句,但是常量没有传递.

这是我的连接声明:

$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());
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*tah 5

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

单独的东西:

config.php

define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'my_username' );
define ( 'DB_PASSWORD', 'my_password' );
define ( 'DB_NAME', 'my_database' );
Run Code Online (Sandbox Code Playgroud)

public/index.php

require_once __DIR__ . '/../config.php';
// The rest of you code here
Run Code Online (Sandbox Code Playgroud)

public/contact.php

require_once __DIR__ . '/../config.php';
// The rest of you code here
Run Code Online (Sandbox Code Playgroud)