archvist
archvist

Reputation: 722

Invalid foreach PDO Error

I'm new to PDO and trying to work as best I can with it I have written the code below but I'm getting an error, Invalid argument supplied for foreach().

This is my code -

<?php 

function sqlConnect()
{
    $mysqlConnection = new PDO('mysql:host=localhost;dbname=students', "root", "root");

    return $mysqlConnection;
}

function getServerResults($costvm)
{
    $sql = "SELECT * FROM ".$costvm;
    $mysqlConnection = sqlConnect();

    $resultSet = $mysqlConnection->query($sql);
    return $resultSet;
}
?>

This is the code written on the error page.

                        try
                        {
                            $resultSet = getServerResults("servers");

                            foreach($resultSet as $row)
                            {
                                echo $row['servername']."<br/>";
                            }
                        } catch(PDOException $e)
                        {
                            echo 'ERROR: '.$e->getMessage();
                        }
                    ?>

Upvotes: 1

Views: 1379

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157839

Get rid of all these functions. Make it straight PDO

$pdo = new PDO('mysql:host=localhost;dbname=students', "root", "root");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$result = $pdo->query("SELECT * FROM servers");
foreach($result as $row)
{
    echo $row['servername']."<br/>";
}

Upvotes: 2

Related Questions