dtcaw02086 2012-12-25 02:37
浏览 72
已采纳

连接MySQL时出现PDO错误[关闭]

I am trying to connect to a MySQL database stored on localhost.

Code:

$config['db'] = array( 
    'host' => 'localhost',
    'username' => 'root',
    'password' => 'mypass',
    'dbname' => "dbname"
);

echo $config['db']['host'];

try {
    $conn = new PDO('mysql:host=127.0.0.1;dbname=sfrtv', 'root', 'usbw', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

This code returns the following error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2003] Can't connect to MySQL server on '127.0.0.1' (10061)' in H:\path\filename.php:12 Stack trace: #0 H:\path\filename.php(12): PDO->__construct('mysql:host=loc....', 'root', 'mypass') #1 {main} thrown in H:\path\filename.php(12) on line 12

Any suggestion on how to correct this?

Thx!

  • 写回答

2条回答 默认 最新

  • doujiao3074 2012-12-25 02:49
    关注

    I am sure you got the code from Alex, in PHP academy. Can you try checking your mysql details are the same. Try this, I changed the quotes and white spaces.

       $config['db'] = array( 
        'host' => 'localhost',
        'username' => 'root',
        'password' => 'mypass',
        'dbname' => 'dbname'
        );
    
            echo $config['db']['host']; 
    
            $dbh = new PDO('mysql:host='. $config['db']['host'] .';dbname='. $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
    

    Or check back the tutorial again: http://www.youtube.com/watch?v=XQjKkNiByCk


    And if not, try this way of connecting with the below code, as it will catch the exception and echo out what the problem is.

    try {
        $conn = new PDO('mysql:host=localhost;dbname=mydb', 'root', 'mypass', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    

    The above way of connecting is much safer, because it something goes wrong it will not display your entire file and directory structure to the user.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大