首页 > 解决方案 > 如何修复警告:为 foreach() 提供的参数无效

问题描述

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

<?php foreach ($user as $key => $value) : ?>警告:在第 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"; ?>

标签: php

解决方案


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

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

    try{

或检查并设置 $user 的值

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

推荐阅读