我目前正在重寫我的舊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