MySql PDO与数据库的连接

时间:2012-10-31 22:04:41

标签: php sql pdo

我正在学习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

1 个答案:

答案 0 :(得分:19)

尝试增加错误模式:

<?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(或类似)获取更多信息,但我认为抛出异常是处理错误连接的更好方法,而不是已解析的主机等。< / p>