PDO-为foreach()提供了无效的参数 [英] PDO - Invalid argument supplied for foreach()
问题描述
我正在尝试输出mysql数据库的内容,但是无论我使用哪种方法出错,这都是我现在正在使用的代码;
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();
}
?>
错误的输出是警告:在第21行的/home/kzkcubcy/public_html/index.php中为foreach()提供了无效的参数"
The error Its outputting is " Warning: Invalid argument supplied for foreach() in /home/kzkcubcy/public_html/index.php on line 21 "
第21行是; "foreach($ dbh-> query($ sql)as $ row)".我已经厌倦了许多其他方法来使它起作用,但是即使从教程中逐字逐句地复制似乎也不起作用.
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.
推荐答案
更改
$dbh = new PDO("mysql:host = $hostname; dbname = kzkcubcy_webDev", $username, $password);
到
$dbh = new PDO("mysql:host=$hostname;dbname=kzkcubcy_webDev", $username, $password);
我认为您不允许在DSN字段中使用空格.
I don't think you are allowed to have spaces in the DSN field.
这篇关于PDO-为foreach()提供了无效的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!