Warning: Invalid argument supplied for foreach ()

1

I have the following select:

public function SelectLastError(){
        try {
            $stmt = $this->conn->prepare("SELECT Name, Data FROM Errors ORDER BY ErrorsId DESC LIMIT 3");
            $stmt->execute();
            while ($row = $stmt->fetch( PDO::FETCH_ASSOC )){
                $rows[] = $row;
            }
        }catch (PDOException $exception){
            echo  $exception->getMessage();
            echo "Error!";
            return null;
        }
    }

And I'm trying to call it HTML like this:

<?php 
  $rows = $selectors->SelectLastError();
  foreach ($rows as $row):?>                            
     <a href="" class="list-group-item">
      <i class="fa fa-bug"></i><?php echo $row['Name'];?>
      <span class="pull-right text-muted small"><em><?php echo $row['Data']?></em>
      </span>
     </a>                                
  <?php endforeach; ?>

I've done this same idea in another foreach, I do not know why this error is appearing, SELECT is right, I've already tested it. Anyone have any ideas?

    
asked by anonymous 03.10.2016 / 20:35

1 answer

4

Tá giving error because its method does not return an iterable value via foreach .

The SelectLastError method should return a array , since you want to use it later on a foreach .

You are adding results to $rows . So you should have returned that too.

See:

function SelectLastError()
{
    try {
        $stmt = $this->conn->prepare("SELECT Name, Data FROM Errors ORDER BY ErrorsId DESC LIMIT 3");
        $stmt->execute();
        while ($row = $stmt->fetch( PDO::FETCH_ASSOC )){
            $rows[] = $row;
        }

        return $rows;

    }catch (PDOException $exception){
        echo  $exception->getMessage();
        echo "Error!";
        return null;
    }
}

Recommendation

If you want to group the results, row by row, in a array , and ultimately return it to use in a function, it would be easier to use a solution that is already present in the language. Instead of using while and save result by result in array , I recommend modifying the method. You are going to replace all of the while with fetchAll .

See:

function SelectLastError () {

    try {

        $stmt = $this->conn->prepare("SELECT Name, Data FROM Errors ORDER BY ErrorsId DESC LIMIT 3");

        $stmt->execute();

        return $stmt->fetchAll( PDO::FETCH_ASSOC);

    }catch (PDOException $exception){
        echo  $exception->getMessage();
        echo "Error!";
        return null;
    }
}
    
03.10.2016 / 20:37