php - 为 mysql 连接定义

标签 php mysql html

我的情况: 文件夹结构是/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/

相关文章:

php - 检查smarty数组中是否存在key

php - 无法通过 OCI 插入度数字符 (°)

mysql - Rails更新数据库方法

mysql - 坚持从 Node 与 RDS/Aurora 对话

javascript - Angularjs - 功能不起作用

php - 从 Symfony 4/5 中的另一个包覆盖包模板

php - CodeIgniter CRUD View 抽象

php - Mysql查询以确定给定的日期时间是否包含在日期时间间隔中

php - 带有大写和小写符号的 .htaccess 和 href 链接

javascript - 粒子js隐藏它下面的网页元素