我的情况: 文件夹结构是/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 语句一起使用,但常量未传递。
这是我的连接语句:
$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 中时,它可以完全正常工作,但我想在各个区域进行连接和关闭连接,我不想再次定义变量
最佳答案
您需要在可通过 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
关于php - 为 mysql 连接定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10423447/