You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP新手求助:foreach函数报错Invalid argument supplied for foreach()

Fixing the "Invalid argument supplied for foreach()" Error in Your PHP Code

Hey there! Let's break down this super common PHP beginner error and fix it step by step—you've got this.

What's Causing the Error?

The foreach() loop only works with arrays (or iterable objects). Looking at your code, the line that actually loads your database data into the $posts variable is commented out:

//$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);

That means $posts is either undefined or holds a non-iterable value (like null), which triggers the error when you try to loop over it.

Step 1: Uncomment the Data-Fetching Line

First, remove the // from that line to populate the $posts array with your database results:

$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);

Step 2: Add a Safety Check for Empty/Invalid Data

Even if you fetch data, your query might return no results (or fail entirely). Adding a simple check before the foreach() loop will prevent errors in those cases:

<?php if (!empty($posts)) : ?>
  <?php foreach ($posts as $post) : ?>
    <!-- Your post display code here -->
  <?php endforeach; ?>
<?php else : ?>
  <p>No posts found.</p>
<?php endif; ?>

Step 3: Add Query Error Handling (Bonus Tip for Beginners)

It's smart to check if your database query ran successfully—this helps catch typos in table/column names or connection issues early:

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

// Check for query errors
if (!$result) {
  die("Query failed: " . mysqli_error($conn));
}

Full Fixed Code

Here's your complete code with all fixes applied:

<?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);

// Check for query errors
if (!$result) {
  die("Query failed: " . mysqli_error($conn));
}

// Fetch Data
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
var_dump($posts); // Keep this for testing, remove it once things work

// Free Result
mysqli_free_result($result);

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

<?php include('inc/header.php'); ?> 
<div class="container">
  <h1>Posts</h1>
  <?php if (!empty($posts)) : ?>
    <?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; ?>
  <?php else : ?>
    <p>No posts available.</p>
  <?php endif; ?>
</div>
<?php include('inc/footer.php'); ?>

Quick Recap for Beginners

  • Always ensure the variable you loop over with foreach() is an array or iterable object
  • Add checks for empty data to avoid unexpected errors
  • Validate your database queries to catch issues early

内容的提问来源于stack exchange,提问作者Andy Terry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:54:37