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.

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

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探