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 Cannot connect to database

I started to learn phalcon long time ago but now I re-learn it again as I forgot how to do things. I tried to use phalcon model to generate model but it threw me an exception:

ERROR: SQLSTATE[HY000] [2002] No such file or directory

and then I tried to check the connection, and apparently I cannot connect to database. My config file is like this:

'database' => [ 'adapter' => 'Mysql', 'host' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'mysite', 'charset' => 'utf8', ],

I don't know what is wrong with my config. Please tell me how to fix it. Thank you.

You still need to take that config and specify a db service with it:

// services.php

use Phalcon\Db\Adapter\Pdo\Factory as DbFactory;

$config = require_once '...path...to...cfg...';

$di->setShared('db', function() use($config) {
    return DbFactory::load($config->database);
});
edited Jul '20

take :) i think you use same as default phalcon app

$di->setShared('db', function () {
    $config = $this->getConfig();

    $class = 'Phalcon\Db\Adapter\Pdo\\' . $config->database->adapter;
    $params = [
        'host'     => $config->database->host,
        'username' => $config->database->username,
        'password' => $config->database->password,
        'dbname'   => $config->database->dbname,
        'charset'  => $config->database->charset
    ];

    if ($config->database->adapter == 'Postgresql') {
        unset($params['charset']);
    }

    return new $class($params);
});


-17

Yes. It has been more than a week since I have faced this issue. No concrete solution yet



8.4k

your issue most likely not in phalcon

try changing localhost to 127.0.0.1

and please provide phalcon and phalcon devtools versions

in terminal/cmd

phalcon info