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!
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.
Make sure you have extension=php_pdo_mysql.dll
enabled/uncommented in your php.ini
file otherwise PDO will not support MySQL.