1

PHP newbie here. I created a cloud MySQL provision using Railway (a Heroku alternative) which I'd like to connect to.

Connecting to the database should be fairly simple, as the service provides a connection url. However, this fails to connect and throws: SQLSTATE[HY000] [2002] No such file or directory.

My attempt at connecting to the db instance:

<?php
try {
  $dsn        = "mysql://root:password@containers-us-west-17.railway.app:7265/railway";
  $username   = "root";
  $password   = "password";
  $options    = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  );

  $connection = new PDO($dsn, $username, $password, $options);
  echo "Database created successfully.";
} catch (PDOException $error) {
  echo $error;
  die();
}
?>

What am I missing?

helio23
  • 11
  • 1

1 Answers1

0

PDO has a specific format, which is unlike URL syntax.

You may not use additional spaces, quotes or slashes in your DSN.

Here a full example for mysql:

$host = 'containers-us-west-17.railway.app';
$port = '7265';
$db   = 'mydatabase';
$user = 'root';
$pass = 'password';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset;port=$port";
try {
    $pdo = new \PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

Your railway database should be at host containers-us-west-17.railway.app on port 7265 based on your URL syntax.

James Risner
  • 5,451
  • 11
  • 25
  • 47