We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Phalcon can't connect to remote mysql

Code:

$di->set('db',function(){   return new \Phalcon\Db\Adapter\Pdo\Mysql(
        array(
          "hosts"=>"developSrv",
          "port"=>"3306",
          "username"=>"root",
          "password"=>"",
          "dbname"=>"test",
          "charset"=>"utf8"
          )  );
});

developSrv is another linux server . Phalcon aways connect to local mysql by mysql.sock. If there is no mysql.sock in local server,Phalcon doesn't work..Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'

How can I do to connect to remote mysql?

It's host, not hosts

$di->set('db',function(){ 
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
      "host"=>"developSrv", //Here
      "port"=>"3306",
      "username"=>"root",
      "password"=>"",
      "dbname"=>"test",
      "charset"=>"utf8"
  ) );
});
edited May '15

I get the same exception:

PDOException: SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

I'm using Phalcon 2.0 and the mysql-server runs on a different host. Here is my config:

return new \Phalcon\Config(array(
    'database' => [
        'adapter'     => 'Mysql',
        'host'        => '192.168.178.12',
        'username'    => 'phalcon',
        'password'    => '***************',
        'dbname'      => 'phalcon',
        'charset'     => 'utf8',
    ],
//...
edited May '15

There is a bug in the phalcon cli tool by scaffolding. In services.php it should be then $config->database->toArray()

$di->set('db', function() use ($config) {
    return new DbAdapter($config->database->toArray());
});
edited May '15

On a new setup macports with mariadb, php56, phalcon 2.0, Old site didn't work. Same connection refused error as above. I changed 'host' => '127.0.0.1' to 'host' => 'localhost', and then it worked. A clue was trying a raw PDO connect call, like this (using a root login). As far as I can tell, PDO tries to treat IP or hostname in the same way in its connection string. Also I seem to remember that I took up with IP before in 1.3 because localhost did not work.

try {
    $pdo = new PDO('mysql:host=localhost', $username, $password);
    echo "Connected using PDO.\n\n";
    $pdo = null;
}
catch(PDOException $e) {
    echo "Error connecting using PDO:\n\n";
    echo "Error ".$e->getCode().": ".$e->getMessage()."\n\n";
}
edited May '15

I was crazy with this bug.

It's line 57 in services.php and for me the error is SQLSTATE[28000] [1045]. I changed $config->toArray() to $config->database->toArray() and fixed the issue.

Thanks Philipp!