dtnd30892 2016-01-24 07:44
浏览 41
已采纳

一个带有奇怪结果的PHP include()函数

I start learning PHP quite recently,and I met a frustrating problem in which the code seems good, but it just won't work,even the one who teach me don't know what cause it. Below I'll paste my code to you.

<?php
header("content-type: text/html; charset = UTF-8");
$con = new mysqli();
$con -> connect("localhost", "root" ,"");
$con -> select_db("test_db");
$con -> query("set names UTF8");
$query = $con -> query("SELECT * FROM TITLES LIMIT 0,2");
$num = $query -> num_rows;
for ($i=1 ; $i <= $num; $i++) 
{ 
    $result = $query -> fetch_array();
    echo "<table style ='float: left'>";
    echo "<tr><th>".$result["TITLE"]."</th><tr>";
    echo "<tr><td>";
    include("$i.php");
    echo "</td></tr>";
    echo "</table>";
}
?>

And the result turn to be this:

enter image description here

By the way,I'm using XAMPP 7.0.1 in MAC.

<?php
header("content-tupe: text/html; charset = UTF-8");
$con = new mysqli();
$con -> connect("localhost", "root" ,"");
$con -> select_db("test_db");
$con -> query("set names UTF8");
$query = $con -> query("SELECT * FROM PHP_MANUAL LIMIT 0,6");
?>
<ul>
<?php
  while ($result = $query -> fetch_array()) 
  {
      echo "<li>".$result["CONTENT"]."</li>";
  }
?>
</ul>
  • 写回答

2条回答 默认 最新

  • douyong8801 2016-01-25 13:31
    关注

    When you include a file in another PHP file all variables in the included file will be active and accessible for manipulation.

    In your case you are using $query and $result variables which override the one you started. So the $query of TITLES has been changed and therefore even if you want to use unset() it won't work.

    Example: Basic include example

    vars.php

    <?php
    
    $color = 'green';
    $fruit = 'apple';
    
    ?>
    

    test.php

    $color = 'yellow';
    $fruit = 'banana';
    
    echo "A $color $fruit"; // A yellow banana
    
    include 'vars.php';
    
    echo "A $color $fruit"; // A green apple
    
    ?>
    

    Source: http://php.net/manual/en/function.include.php

    Also the $con variable you may want to put in a separated PHP file and included once. Read more about PHP include:

    http://php.net/manual/en/function.include-once.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探