无法使foreach函数工作,不断调用错误

时间:2018-03-23 15:07:14

标签: php foreach

**更新了代码并包含完整代码**

我目前正在学习PHP,而且我遇到了这个为foreach()错误提供的无效参数,我已经尝试了一切,似乎没有任何地方,考虑到我学习PHP,请温柔。

    <?php
    require('config/config.php');
    require('config/db.php');

    // Create Query
    $query = 'SELECT * FROM posts ORDER BY created_at DESC';

    // Get Result
    $result = mysqli_query($conn, $query);

    // Fetch Data
    //$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
    var_dump($posts);

    // Free Result
    mysqli_free_result($result);

    // Close Connection
    mysqli_close($conn);
?>





<?php include('inc/header.php'); ?>
    <div class="container">
        <h1>Posts</h1>

        <?php foreach ($posts as $post) : ?>
            <div class="well">
                <h3><?php echo $post['title']; ?></h3>
                <small>Created on <?php echo $post['created_at']; ?> by <?php echo $post['author']; ?></small>
                <p><?php echo $post['body']; ?></p>
                <a class="btn btn-default" href="<?php echo ROOT_URL; ?>post.php?id=<?php echo $post['id']; ?>">Read More</a>
            </div>
        <?php endforeach; ?>
    </div>
<?php include('inc/footer.php'); ?>

3 个答案:

答案 0 :(得分:0)

很可能你没有在$ posts中获得数组。尝试var_dumping它。

一个干净的代码可以优雅地处理这种情况......

if (is_array($posts) || is_object($posts))
{
    foreach ($posts as $post)
    {
        ...
    }
}

答案 1 :(得分:0)

我猜你忘了设置你想要显示的每个元素。确保你有一个有效的数组,如

<?php
$posts[0]['title']      = '1';
$posts[0]['created_at'] = '2';
$posts[0]['author']     = '3';
$posts[0]['body']       = '4';
?>

其中一个('title','created_at','author','body')未在数组中设置。

答案 2 :(得分:0)

<?php
    require('config/config.php');
    require('config/db.php');

    // Create Query
    $query = 'SELECT * FROM posts ORDER BY created_at DESC';

    // Get Result
    $result = mysqli_query($conn, $query);

    // Fetch Data

    ////////////////////////////////////////////////////////
    ////    REMOVE THE COMMENT MARK ON THE LINE BELOW   ////
    ////////////////////////////////////////////////////////
    $posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
    var_dump($posts);

?>

如果

$post

未设置,

foreach

第26行可能会返回错误。