MySql PDO连接数据库 [英] MySql PDO connection to database

查看:82
本文介绍了MySql PDO连接数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 :

<?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

推荐答案

尝试增加错误模式:

<?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.errorcode

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

这篇关于MySql PDO连接数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆