我試圖將連接到數據庫的過程卸載到DBConfig.php文件,正如任何地方建議的那樣,因爲我需要重用幾個文件中的代碼。PHP Require()在父代碼範圍內不執行所需的文件
的建議總是被誣陷爲(編輯以反映我實際的代碼):
-------DBConfig.php-------
<?php
$link = mysql_connect('localhost','user','pass');
if (!$link) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('db_name');
if (!$db_selected) {
die ('Can\'t use db_name : ' . mysql_error());
}
?>
-------Parent.php-------
<!DOCTYPE html>
<?php
require_once 'DBConfig.php';
$something = mysql_query("SELECT * FROM `table` LIMIT 0, 30 ");
// This query works fine if the mysql_connect() and
// mysql_select_db() stuff is in this script in place
// of the require_once.
$listofthings = array();
while($temp = mysql_fetch_array($something)){
$listofthings[] = $temp;
}
// Do other things too
?>
但是,當我嘗試做mysql_fetch_array($something)
,它失敗的警告:mysql_fetch_array() expects parameter 1 to be resource, boolean given
。
記住,一切精美的作品,如果我只是下降的DBConfig.php
內容到父腳本,而不是require 'DBConfig.php';
...
還注意到print(require 'DBConfig.php'); //- 1
(PHP函數返回一個1,表明它正在成功定位幷包含該文件,請參閱example 5)...
發生了什麼,以及如何解決該問題?我使用在Windows 7 x64上運行的WAMPServer(Apache 2.4.2,PHP 5.4.3)的默認配置。
幾件事情很快:您應該使用'<?php'標籤而不是短標籤。而且,避免使用'mysql_ *'函數,因爲它們已被棄用。 – Prasanth
你嘗試在mysql_query()函數調用後包含文件嗎? – ioseb
當沒有結果時,'mysql_fetch_array'返回'false'。這可能解釋'布爾給定'部分。你檢查行是否被返回? –