My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Can anyone Please help me out With this. Foreach Error seems Endless - PHP

Williams Isaac's photo
Williams Isaac
·Jun 26, 2016

Hi Gi, Please what wrong with my code. I have been trying it out for ours now.

<?php
    include 'models/database.php';
    $pdo = Database::connect();
    $sql = 'SELECT * FROM customers ORDER BY staff_id DESC';
    foreach ($pdo->query($sql) as $row) {
    echo '<tr>';
    echo '<td>'. $row['surname'] . '</td>';
    echo '<td>'. $row['firstname'] . '</td>';
    echo '<td>'. $row['sex'] . '</td>';
    echo '<td>'. $row['dateofbirth'] . '</td>';
    echo '<td>'. $row['qualification'] . '</td>';
    echo '<td>'. $row['department'] . '</td>';
    echo '<td>'. $row['yearjoined'] . '</td>';
    echo '<td>'. $row['email'] . '</td>';
    echo '<td width=250>';
    echo '<a class="btn" href="read.php?id='.$row['staff_id'].'">Read</a>';
    echo ' ';
    echo '<a class="btn btn-success" href="update.php?id='.$row['staff_id'].'">Update</a>';
    echo ' ';
    echo '<a class="btn btn-danger" href="delete.php?id='.$row['staff_id'].'">Delete</a>';
    echo '</td>';

    echo '</tr>';
    }

    Database::disconnect();
?>

and I have a database like this

<?php
    class Database
    {
    private static $dbName = 'terminal' ;
    private static $dbHost = 'localhost' ;
    private static $dbUsername = 'root';
    private static $dbUserPassword = '';
    private static $cont = null;
    public function __construct() {
    die('Init function is not allowed');
    }
    public static function connect()
    {
    // One connection through whole application
    if ( null == self::$cont )
    { 
    try
    {
    self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword); 
    }
    catch(PDOException $e)
    {
    die($e->getMessage()); 
    }
    }
    return self::$cont;
    }
    public static function disconnect()
    {
    self::$cont = null;
    }
    }
?>

it keeps showing Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\Payroll\viewstaffs.php on line 50 but when i change the name of the database to something esle like from terminal to payroll, the code works with out an error. Please can anyone help me check it out