为什么我不能通过终端运行有效的PDO连接?

My working index.php that runs in a browser looks like this:

<?php
    $dbh = new PDO(...whatever

It works in a bowser just fine. I can do anything.

Running in terminal like:

shell> php index.php

I get some error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] No such file or directory' in /Library/WebServer/Documents/index.php:3
Stack trace:
#0 /Library/WebServer/Documents/index.php(3): PDO->__construct('mysql:host=loca...', 'root', 'frekinpassword')
#1 {main}
  thrown in /Library/WebServer/Documents/index.php on line 3

What's going on here?

I think, your unix_socket changed and you didn't change your php client php.ini

First of all, get your unix_socket location.

$ mysql -uroot -p

Enter your mysql password and login your mysql server from command line.

mysql> show variables like '%sock%';
+---------------+---------------------------------------+
| Variable_name | Value                                 |
+---------------+---------------------------------------+
| socket        | /opt/local/var/run/mysql5/mysqld.sock |
+---------------+---------------------------------------+

Your unix_soket could be diffrent.

Then change your php.ini, find your php.ini file from

<? phpinfo();

You maybe install many php with different version, so please don't assume your php.ini file location, get it from your 'phpinfo';

Change your php.ini:

mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock

mysqli.default_socket = /opt/local/var/run/mysql5/mysqld.sock

pdo_mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock

Then restart your apache or php-fpm.

It looks like you're using localhost as the connection string for your MySQL database. When MySQL sees localhost, it interprets that as "use a mysql.sock" file. PHP is telling you it can't find that mysql.sock file.

The most likely cause for this is your web server and command line PHP are configured to use different php.ini files, and those php.ini files have differently configured mysql.sock files. You can find your web server php.ini file(s) by running

phpinfo();

from a PHP file loaded via the web server. You can find your command line php.ini file(s) by running the following

$ php --ini

If you can't fix your command line php.ini file, consider connecting to your MySQL server via 127.0.0.1 instead of localhost. When you use the IP address, PHP should attempt to connect via the network instead of a socket file.