Answer the question
In order to leave comments, you need to log in
Why is PDO not connecting locally?
I am using OpenServer. Writing:
define('DB_HOSTNAME', '127.0.0.1:3310');
define('DB_USERNAME', 'mysql');
define('DB_PASSWORD', 'mysql');
define('DB_DATABASE', 'mydb');
function joinPairs(array $map, $kvSeparator = '=', $itemsSeparator = ';') {
$result = [];
foreach ($map as $key => $value) {
$result[] = "${key}${kvSeparator}${value}";
}
return implode($itemsSeparator, $result);
}
$hostParts = explode(':', DB_HOSTNAME);
$dsn = 'mysql:' . joinPairs([
'host' => $hostParts[0],
'port' => $hostParts[1],
'dbname' => DB_DATABASE,
'charset' => 'utf8',
]);
try {
$db = new PDO($dsn, DB_USERNAME, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "set names 'utf8'",
]);
} catch (PDOException $e) {
die($e->getMessage());
}
Answer the question
In order to leave comments, you need to log in
Don't go to localhost, go to an external address. An error like "Connection refused", and most likely, the mysql-server forbids walking locally by additional parameters (say, there is a check in /etc/passwd, and the user is local to the server).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question