I'm trying to connect to my database using PDO but i can't get it working. I get a 500 server error
MySQL version 5.0.83
'PDOException' with message 'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known' inerror: Fatal error: Uncaught exception
Other error i get:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Operation timed out'
I changed the values in this example obviously. And yes they are the correct credentials. I can connect with Sequel Pro or other methods.
connection.php:
<?php
//Our MySQL user account.
define('MYSQL_USER', 'user');
//Our MySQL password.
define('MYSQL_PASSWORD', 'pass');
//The server that MySQL is located on.
define('MYSQL_HOST', 'host');
//The name of our database.
define('MYSQL_DATABASE', 'database');
/**
* PDO options / configuration details.
* I'm going to set the error mode to "Exceptions".
* I'm also going to turn off emulated prepared statements.
*/
$pdoOptions = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
/**
* Connect to MySQL and instantiate the PDO object.
*/
$pdo = new PDO(
"mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, //DSN
MYSQL_USER, //Username
MYSQL_PASSWORD, //Password
$pdoOptions //Options
);
Registration.php
<?php
require 'connection.php';
The strange thing is that on an older page of this website mysql_connect() is used.
$db = mysql_connect($hostname, $db_user, $db_password); mysql_select_db($database,$db);
This works perfect with the exact same credentials.
It's hosted on a shared hosting and PDO is enabled on the server. Shared Hosting: Blacknight
I tried:
- Not using $pdoOptions
- Not using define()
- Not using require and putting the new pdo code straight into the registration.php file
- running the script in the answers and now my mysql_connect() does a time-out and on my hosting i get a whitescreen.
now: Fri, 15 Jan 2016 08:54:21 +0100 last changed:Fri, 15 Jan 2016 08:53:01 +0100 Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in connection.php on line 14
Warning: mysql_connect(): Operation timed out in connectie.php on line 14 connection failed. Operation timed out
mysql_connect
fails for the same reason, but you're not actually checking for that, and when calling subsequentmysql_
functions they do their ugly implicit behind-the-scenes best-guess connection which happens to work. - decezehttp://mysql640int.cp.blacknight.com
would also be wrong. - VolkerKvar_dump( MYSQL_HOST, gethostbyname(MYSQL_HOST)); die;
right before$pdo = new PDO
should display the host name (only once) and the IP address of that server. Does it? - VolkerK