【发布时间】:2017-12-29 00:44:08
【问题描述】:
我在 header.php 文件中调用了一个数据库配置文件 (db_config.php)。我在我的模板(location.php)中调用 header.php 我需要访问 db 配置文件中的变量,因为我正在运行返回结果的查询,然后我在模板中调用它。
所以在我的 db_config.php 文件中,我有以下内容:
$area_query = "SELECT * FROM `locations` where `type` = 'area'";
mysqli_query($db, $area_query) or die('Error querying database.');
$area_result = mysqli_query($db, $area_query);
if (!$area_result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
然后在一个名为 locations.php 的文件中,我正在循环遍历结果 以上使用:
while ($row = mysqli_fetch_array($area_result))
{
echo "<li class='location-list-item'><a href='location/$row[name]'><span class='initial-letter'>".mb_substr($row['name'],0,1)."</span>".$row['name']." <i class=\"fa fa-chevron-circle-right\" aria-hidden=\"true\"></i></a></li>";
}
如果我使用以下方法在 header.php 中包含 db_config.php,这将正常工作:
include("config/db_config.php");
但是,如果我使用:
include($_SERVER['DOCUMENT_ROOT']."/config/db_config.php");
它按预期找到了 db_config.php(访问locations.php 文件时在db_config.php 输出中回显某些内容),但我无法访问$area_result。我收到以下错误:
Notice
: Undefined variable: area_result
on line
28
Warning
: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null
given in
locations.php
on line
28
我很困惑为什么使用 $_SERVER['DOCUMENT_ROOT'] 会阻止我访问变量?出于文件路径的原因,我需要使用 $_SERVER['DOCUMENT_ROOT']。
为了澄清,我在locations.php 中包含了header.php,而header.php 又包含了db_config.php。我可以在 db_config 中回显访问locations.php 时输出的内容,但我无法访问变量。
谢谢。
【问题讨论】:
-
谢谢,在那里尝试了一些东西,但都没有奏效。
标签: php variables document-root server-side-includes