我目前正在重写我的旧PHP脚本,以便代码结构良好,以便将来更新。文件包含可能的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;
}
}
我以前的代码曾经完美地工作,但是现在我已经将变量转换为不同的文件,即我的应用程序不断输出“无法选择父母的晚餐桌。 “ - 这意味着我的应用程序没有正确连接到数据库。
有没有人有任何想法我的代码有什么问题?我认为这是一个范围问题,但我只是无法找出什么我做错了这里。提前
感谢您的任何答复。
现在修复它,谢谢! :)我觉得有点傻,因为我没有想到自己! – 2012-03-20 23:41:53
没问题。很高兴我能帮上忙。 – dqhendricks 2012-03-20 23:52:09