user3671340
user3671340

Reputation: 1

How to fix Warning: Invalid argument supplied for foreach()

I'm setting an edit user page on my local machine using PHP. There is this error

Warning: Invalid argument supplied for foreach() on line 79(<?php foreach ($user as $key => $value) : ?>)

I have tried to solve it, but in vain. I'm kinda new to PHP. Maybe there is something that I am missing or not seeing. Kindly assist and correct me if need be. Below is my code from the update.php page.

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

Upvotes: 0

Views: 71

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34914

You are not setting any value for initial loading for variable $user, so it is undefined in foreach, so either use

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

    try{

Or check and set value for $user

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

Upvotes: 1

Related Questions