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 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?