gpt4 book ai didi

PHP Require() 不在父脚本范围内执行所需文件

转载 作者:行者123 更新时间:2023-12-04 05:26:51 27 4
gpt4 key购买 nike

正如几乎所有地方所建议的那样,我正在尝试将连接到数据库的过程卸载到 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com