dongwei1921 2012-12-18 04:36
浏览 86
已采纳

PDO - 为foreach()提供的参数无效

I'm attempting to output the contents of my mysql database but no matter what method I use it errors, here is the code I'm using now;

try 
{
    $dbh = new PDO("mysql:host = $hostname; dbname = kzkcubcy_webDev", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database<br />';

    /*** The SQL SELECT statement ***/
    $sql = "SELECT * FROM animals";
    foreach ($dbh->query($sql) as $row)
    {
        print $row['animal_type'] .' - '. $row['animal_name'] . '<br />';
    }

    /*** close the database connection ***/
    $dbh = null;
}
catch(PDOException $e)
{
    echo $e->getMessage();
}
?>

The error Its outputting is " Warning: Invalid argument supplied for foreach() in /home/kzkcubcy/public_html/index.php on line 21 "

and line 21 is; " foreach ($dbh->query($sql) as $row) ". I've tired so many other methods at getting this to work but even copying word for word from tutorials doesn't seem to work.

  • 写回答

1条回答 默认 最新

  • dpthuyh1678 2012-12-18 04:41
    关注

    change

    $dbh = new PDO("mysql:host = $hostname; dbname = kzkcubcy_webDev", $username, $password);
    

    to

    $dbh = new PDO("mysql:host=$hostname;dbname=kzkcubcy_webDev", $username, $password);
    

    I don't think you are allowed to have spaces in the DSN field.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?