php include()赢得';不起作用


php include() won't work?

include()函数在代码中工作时遇到问题。基本上,我有一个$order数组,它有我的页面在中显示的顺序

在这种情况下:页码:1,2,3,4,5,6,如$order数组中所示。

如果我只发布了6个带有确切路径的include()函数,就会显示页面,但如果我试图将它们包含在这个for()循环中,那就行不通了。

$order Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

$fields = 6;

奇怪的是,如果我让数组4,5,6,1,2,3完美工作:

$order Array ( [0] => 4 [1] => 5 [2] => 6 [3] => 1 [4] => 2 [5] => 3 )

仅显示前3页

for($x = 0; $x < $fields; $x++)
{
      $page_info = mysql_query("SELECT * FROM pages WHERE id='" . $order[$x] ."'");
      $pageInfo = mysql_fetch_array($page_info);
      $pageNum = $pageInfo['id'];
      if($pageNum <= 6)
      {
           $pagePath = "page" . $pageNum . ".php";
           include($pagePath);
      }
}

令人困惑的是,我知道它正在读取每个$pageInfo['id'],因为这是以下输出:

输出:123456

for($x = 0; $x < $fields; $x++)
{
      $page_info = mysql_query("SELECT * FROM pages WHERE id='" . $order[$x] ."'");
      $pageInfo = mysql_fetch_array($page_info);
      echo $pageInfo['id'];
}

这是有效的

include("page1.php");
include("page2.php");
include("page3.php");
include("page4.php");
include("page5.php");
include("page6.php");

您可能在其中一个include中将$x设置为某个数字。如果它只显示前三个,那么在page3.php中可能有类似$x = 7;的内容。

很明显,您会看到您期望看到的数字(1-6),因为您正在将它们打印到屏幕上。您尝试过使用trim的建议,但没有得到任何进一步的帮助。

我的假设是,用于调试的echo位于if语句之外,并且if语句并不是每次都在运行。首先,尝试将echo放入if语句中,以确保输出相同,然后将var_dump($pagePath);也放入其中,以确保变量符合预期。

你可以尝试的另一件事是,你可以确保文件存在:

echo (file_exists($pagePath)) ? 'Exists' : 'Does not exist...';

您可以在包含的文件中向我们发布代码,以检查您是否覆盖了包含中的$x$pageNum等变量-变量在包含之间是全局的,并且会相互覆盖。

最后,我知道你会对此有一个很好的解释,但对我来说,这看起来很冗长,在这个特定的应用程序中,你可以这样做:

for($i=1;$i<=6;$i++){包括"page"$我。php';}

旁注:

mysql_*函数已弃用,您应该使用PDO或mysqli。资源:-http://php.net/manual/en/book.pdo.php-http://php.net/manual/en/book.mysqli.php

PHP的include函数是一种语言控制结构,而不是函数,因此不应该与括号一起使用:

// good:
include 'filename.php';
// bad:
include('filename.php');

1)我不建议在循环中获取DB,而是保留您的示例:你可以在你的循环中尝试类似的东西

if($pageNum ){ //lets omit the <=6 for the test.
  $pagePath = "page" . $pageNum . ".php";
  echo "include($pagePath);";
}

检查一下结果,也许你得到了与你预期不同的东西。

试试这个

for($x = 0; $x < count($order); $x++)
{
      $page_info = mysql_query("SELECT * FROM pages WHERE id=" . $order[$x]);
      $pageInfo = mysql_fetch_array($page_info);
      foreach($pageInfo as $p_info)
      {
          $pageNum = $p_info['id'];
          break;
      }
  if($pageNum <= 6)
  {
       $pagePath = "page" . $pageNum . ".php";
       require_once($pagePath);//If it can't find the file then it will kill page and show corresponding error
  }

}