6

我正在学习 PDO,我很困惑,我在下面有这段代码,对我来说一切正常,但是我收到了这个错误代码,我不知道该怎么做才能修复它,请帮助我:

<?php
$hostname='localhost';
$username='root';
$password='';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=stickercollections",$username,$password);
    echo 'Connected to Database<br/>';
    
    $sql = "SELECT * FROM stickercollections";
foreach ($dbh->query($sql) as $row)
    {
    echo $row["collection_brand"] ." - ". $row["collection_year"] ."<br/>";
    }
    
    
    $dbh = null;
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?> 

错误代码

Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/GOTSWAPMAIN/index.php on line 11
4

1 回答 1

23

尝试增加错误模式:

<?php
$hostname='localhost';
$username='root';
$password='';

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

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
    echo 'Connected to Database<br/>';

    $sql = "SELECT * FROM stickercollections";
foreach ($dbh->query($sql) as $row)
    {
    echo $row["collection_brand"] ." - ". $row["collection_year"] ."<br/>";
    }


    $dbh = null;
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?> 

编辑: pdo.error-handling说,您可以选择使用pdo.errorcodepdostatement.errorcode(或类似)来获取更多信息,但我认为抛出异常是处理不良连接的更好方法,而不是解决主机等。

于 2012-10-31T22:23:05.737 回答