Ewan Delanoy
Ewan Delanoy

Reputation: 1282

MySQL connection via Unix socket works with mysqli but not with PDO

I'm using MAMP 5.5.42 with PHP 5.6.7 on my Mac OS 10.11.3. The code snippet is as follows :

try{
$db = new PDO('mysql:host=localhost:8889;dbname=lacolshow_database;charset=utf8', 'root', 'root');
}
catch (PDOException $e) {
    var_dump($e->getMessage());
}

The code above raises no exception, but produces an empty PDO object.

If localhost:8889 is replaced by just localhost in the code above, an exception is raised with message SQLSTATE[HY000] [2002] No such file or directory.

If localhost:8889 is replaced by 127.0.0.1 in the code above, an exception is raised with message SQLSTATE[HY000] [2002] Connection refused.

Any help appreciated.

Update: the connection works if I use mysqli instead of PDO :

$mysqli=mysqli_connect('localhost', 'root', 'root', 'lacolshow_database', NULL, '/Applications/MAMP/tmp/mysql/mysql.sock');

Following the advice given in the second comment at http://php.net/manual/en/pdo.construct.php, I tried the following :

$dsn = 'mysql:dbname=lacolshow_database;unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock';
$db = new PDO($dsn,'root', 'root');

but that fails too, producing an empty PDO object.

Upvotes: 0

Views: 4976

Answers (2)

Rohit Gaikwad
Rohit Gaikwad

Reputation: 3914

1) You need to add the port number in the connection string to connect with your DB. Your DB server is running at port no.: 8889 in your local environment, so localhost:8889 used in DB connection string will not raise any exception.

2) If you replace localhost:8889 by localhost then the connection will not establish and an error with message SQLSTATE[HY000] [2002] No such file or directory will occur that indicates a MySQL connection via socket is tried (which is not supported).

3) When you use 127.0.0.1 a connection attempt will be made but will be refused, SQLSTATE[HY000] [2002] Connection refused. It means the SQL database was either offline or being accessed incorrectly. Perhaps an incorrect port or socket path.

Hence, the first point is correct way to establish a connection with DB server.

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157839

The port is going into distinct parameter, not into host. So it should be

$db = new PDO('mysql:host=localhost;port=8889;dbname=lacolshow_database;charset=utf8', 'root', 'root');

Note that you don't have to catch and var_dump an exception, PHP will show you it by itself

Upvotes: 2

Related Questions