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 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0