An Exception PDO occurs when localhost is used as host


Consider the following adapter class DbAdapterMySQL that extends the class PDO :

class DbAdapterMySQL extends \PDO implements DbInterface

    public function __construct(array $config)
        $dsn = "mysql:dbname={$config['dbname']};host={$config['host']}";

        //A próxima linha é a 13
        parent::__construct($dsn, $config['username'], $config['passwd']);


Notice that for the constructor method an array with database access settings is passed with the following structure:

db = MySQL
dbname = teste
username = 'root'
passwd = 'root'
host =

So far, everything works perfectly, but if you replace the value of% index with% with% with%, the following error is returned:


Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE [HY000] [2002] No such file or directory' in /home/filipe/projects/teste/lib/vendor/Testes/Db/Adapter/DbAdapterMySQL.php : 13 Stack trace: # 0   in /home/filipe/projects/teste/lib/vendor/Testes/Db/Adapter/DbAdapterMySQL.php on line 13

Why does the error occur while using host ?

asked by anonymous 29.02.2016 / 16:22

1 answer


It seems that the problem is related to PHP's connection to MySQL.

So I understand, when we use localhost as a host, PHP uses socket to connect to MySQL, different from when we use where the connection is made through TCP / IP.

If you use a Linux-based system, there must be a my.cnf configuration file that is used to configure MySQL.

In my case as I am using Ubuntu, the file is in the /etc/mysql/ directory and there is a line like this:

socket = /var/run/mysqld/mysqld.sock

PHP needs to use the same file and in my case it was not the same as MySQL used.

To correct the problem, I changed the php.ini by adding the directory where the socket file was located:

mysql.default_socket = /var/run/mysqld/mysqld.sock
mysqli.default_socket = /var/run/mysqld/mysqld.sock
pdo_mysql.default_socket = /var/run/mysqld/mysqld.sock

After the change, I just restarted apache:

sudo service apache2 restart

29.02.2016 / 17:00