【发布时间】:2012-04-05 11:53:12
【问题描述】:
我目前正在重写我的一个旧 PHP 脚本,以便代码结构良好,以供将来更新。
我正在尝试做的一件事是创建一个配置文件 - 以便可以通过编辑一个文件轻松更改设置。
文件源代码:functions.php
function ConnectToDB() {
//database configurations...
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$tblname = "parents";
$connection = mysql_connect($host,$dbuser,$dbpass);
if (!$connection) {
echo 'Could not connect to the database. Please contact the administrator for more information.';
}
// select the db
$db_selected = mysql_select_db($tblname, $connection);
if (!$db_selected) {
echo 'Could not select the parents evening table. Please contact the administrator for more information.';
return false;
}else{
return true;
}
}
文件:config.php
<?php
//database configurations...
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$tblname = "parents";
?>
这是我的新代码: 文件:functions.php
function ConnectToDB() {
include('inc/config.php');
global $host; //needed becuase the scope of the variable throws an error otherwise.
global $dbuser; //needed becuase the scope of the variable throws an error otherwise.
global $dbpass; //needed becuase the scope of the variable throws an error otherwise.
global $tblname; //needed becuase the scope of the variable throws an error otherwise.
$connection = mysql_connect($host,$dbuser,$dbpass);
if (!$connection) {
echo 'Could not connect to the database. Please contact the administrator for more information.';
}
// select the db
$db_selected = mysql_select_db($tblname, $connection);
if (!$db_selected) {
echo 'Could not select the parents evening table. Please contact the administrator for more information.';
return false;
}else{
return true;
}
}
我的旧代码过去可以完美运行,但是现在我将变量更改为不同的文件,我的应用程序不断输出“无法选择父母的晚宴桌。请联系管理员以获取更多信息。” - 这意味着我的应用程序没有正确连接到数据库。
有人知道我的代码有什么问题吗?起初我认为这是一个范围问题,但是我在这里找不到我做错了什么。
提前感谢您的任何回复。
【问题讨论】:
标签: php mysql database file include