如何检查我的 foreach 循环是否有错误


How to check if my foreach loop has a bug?

我只是快速为一个文章网站编写了一个脚本,在那里我从数据库中检索文章。

这是我的索引.php脚本

    <?php
    // include header
    require("include/header.php");
    require("include/helperfunctions.inc.php");
    ?>
    <!-- page content -->
    <!-- left section -->
    <section id="contentleft">
<?php require("include/functions.php"); 
displayArticles();
foreach ($articles as $article) : ;
?>
<h2>Recent Articles</h2>
    <ul>
        <li><?php echo htmlout($articles['id']) ; ?></li>
        <li><?php echo htmlout($articles['title']) ; ?></li>
        <li><?php echo htmlout($articles['summary']) ; ?></li>
    </ul>
<?php endforeach; ?>
    </section>
    <!-- right content -->
    <section id="contentright">
    </section>
    <?php
    // include footer
    require("include/footer.php");
    ?>

这是函数库的开始

    function displayArticles($order="publicationdate DESC"){
        // connect to the database
        include("include/db.inc.php");
    $query = "SELECT id, title, summary FROM maths order by ". $order . " limit 10";
// query the database
$result = mysqli_query($link, $query);
    // error checking
    if(mysqli_connect_errno()){
    // $error = "error fetching articles";
    echo " could not connect: " . mysqli_connect_errno() . " ";
    exit();     
}
// loop through storing values into array
while($row = mysqli_fetch_array($result)){
    $articles[] = array('id'=>$row['id'] , 'title'=>$row['title'],'summary'=>$row['summary']);        
}
    }
    ?>

我收到此错误:

警告:mysqli_fetch_array() 期望参数 1 mysqli_result,在第 17 行的 C:''Apache24''htdocs''include''functions.php 中给出的布尔值 最近的文章 注意:未定义的变量:C:''Apache24''htdocs''home.php 第 14 行中的文章 警告:在第

14 行的 C:''Apache24''htdocs''home.php 中为 foreach() 提供的参数无效

它看起来像是$articles对象的作用域问题。您可以在 displayArticles() 函数中创建$articles。但是在函数之外,您的其他代码不知道它。尝试在 displayArticles() 中返回 $articles,并替换您的 displayArticles();在第一页顶部拨打:

$articles = displayArticles();

此外,正如 panique 在评论中指出的那样,您在 foreach 块中引用了错误的对象。删除每个$articles末尾的"s"[blah],使其显示为$article[blah]。