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条)

报告相同问题?