Php 如何修复警告:为foreach()提供的参数无效

Php 如何修复警告:为foreach()提供的参数无效,php,Php,我正在使用PHP在本地机器上设置一个编辑用户页面。有一个错误 警告:为第79行的foreach()提供的参数无效() 我曾试图解决它,但徒劳无功。我对PHP有点陌生。也许有些东西我错过了或没有看到。如果需要,请帮助并纠正我。下面是我在update.php页面上的代码 <?php ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); inclu

我正在使用PHP在本地机器上设置一个编辑用户页面。有一个错误

警告:为第79行的foreach()提供的参数无效(

我曾试图解决它,但徒劳无功。我对PHP有点陌生。也许有些东西我错过了或没有看到。如果需要,请帮助并纠正我。下面是我在update.php页面上的代码

<?php 

 ini_set('display_errors', '1');
 ini_set('display_startup_errors', '1');
 error_reporting(E_ALL);
 include_once 'core/init.php'; 
 require 'common.php'; //Escapes HTML for output
if (isset($_POST['submit'])) { 

try{
      $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);

$user = [
      "id"        => $_POST['id'],
      "username"  => $_POST['username'],
      "email"     => $_POST['email'],
      "join_date" => $_POST['join_date']
    ];

 $DB->query ('UPDATE users 
        SET id = :id, 
        username = :username, 
        email = :email, 
        join_date = :join_date
        WHERE id = :id');

$DB->execute();

}
catch(PDOException $e){

    echo $this->error = $e->getMessage();
 }

}

if (isset($_GET['id'])) {

    try{
         $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);

         $id = $_GET['id'];

         $DB->query('SELECT * FROM users WHERE id = :id');

         $DB->bind(':id', $id);

         $DB->execute();

         $result=$DB->resultset();

        // Catch any errors
        }
        catch(PDOException $e){

           echo $this->error = $e->getMessage();

        }
    }


?>

<?php include "templates/header.php"; ?>


<?php if (isset($_POST['submit']) && $DB) : ?>

    <blockquote><?php echo escape($_POST['username']); ?> successfully updated.</blockquote>

<?php endif; ?>

<h2>Edit a user</h2>

<form method="post">

    <?php foreach ($user as $key => $value) : ?>

      <label for="<?php echo $key; ?>"><?php echo ucfirst($key); ?></label>

        <input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'id' ? 'readonly' : null); ?> >

<?php endforeach; ?> 



 <input type="submit" name="submit" value="Submit">
</form>

<a href="http://localhost/form/home.php">Back to home</a>

<?php include "templates/footer.php"; ?>

已成功更新。
编辑用户

您没有为变量$user的初始加载设置任何值,因此它在
foreach
中未定义,因此使用

  $user = [];
  if (isset($_POST['submit'])) { 

    try{
或者检查并设置$user的值

   <?php foreach ($user ?? [] as $key => $value) : ?>

非常感谢,这对我来说确实有效$user=[];如果(设置($_POST['submit']){try{