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

use*_*794 2 php mysql pdo

我正在尝试输出我的mysql数据库的内容,但无论我使用什么方法错误,这里是我现在使用的代码;

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();
}
?>
Run Code Online (Sandbox Code Playgroud)

错误输出为"警告:在第21行的/home/kzkcubcy/public_html/index.php中为foreach()提供的参数无效"

和第21行是; "foreach($ dbh-> query($ sql)as $ row)".我已经厌倦了许多其他方法来实现这一点,但即使从教程中逐字逐句复制也似乎不起作用.

cry*_*c ツ 5

更改

$dbh = new PDO("mysql:host = $hostname; dbname = kzkcubcy_webDev", $username, $password);
Run Code Online (Sandbox Code Playgroud)

$dbh = new PDO("mysql:host=$hostname;dbname=kzkcubcy_webDev", $username, $password);
Run Code Online (Sandbox Code Playgroud)

我认为您不允许在DSN字段中包含空格.