php MySql PDO 连接到数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13168120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:52:25  来源:igfitidea点击:

MySql PDO connection to database

phpsqlpdo

提问by Marc Guerin

I am learning PDO and i am getting very confused, I have this piece of code below and all look right to me however am getting this error code and i dont know what I have to do to fix it, please help me :

我正在学习 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();
    }
?> 


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

错误代码 : Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/GOTSWAPMAIN/index.php on line 11

回答by Anton Bessonov

Try to increase error mode:

尝试增加错误模式:

<?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();
    }
?> 

EDIT:pdo.error-handlingsays, you can alternatively use pdo.errorcodeand pdostatement.errorcode(or like) to get more info, but I think throw exception is better way to handle bad connections, not resolved hosts etc.

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