我正在尝试将连接数据库的过程卸载到 DBConfig.php 文件,正如几乎所有地方所建议的那样,因为我需要在多个文件中重用代码。
该建议始终被定义为(经过编辑以反射(reflect)我的实际代码):
-------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 )...
这是怎么回事,我该如何解决?我使用 WAMPServer 的默认配置(Apache 2.4.2、PHP 5.4.3),在 Windows 7 x64 上运行。
最佳答案
如果这样
require 'DBConfig.php';
实际上是您正在做的事情,脚本绝对不可能在其他范围内执行。如果您使用的是 http://
URL,这可能是原因,但如果您像您一样使用相对路径,则不会。
在连接到数据库之后,也没有在 mysql_query()
调用之后进行任何错误检查,因此更有可能只是查询中断。为您的查询添加适当的错误检查,您就会了解更多。
另一种可能性是如果您在函数内调用DBConfig.php
。函数会扰乱您的包含范围。但您的示例中没有,所以我假设这不是问题所在。
关于PHP Require() 不在父脚本范围内执行所需文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13102226/