Home >Database >Mysql Tutorial >Why am I getting \'No such file or directory\' error when connecting to MySQL via PDO?
You may encounter the following error while trying to connect to a MySQL database using PDO:
Warning: PDO::__construct(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in ...
This error occurs when PDO attempts to connect to MySQL through a Unix socket, but your code is configured for TCP/IP connection.
You can resolve this issue by specifying the correct connection parameters in your PDO constructor. Instead of using "localhost" as the hostname, use "127.0.0.1" to indicate a TCP/IP connection to the local machine.
<code class="php">new PDO('mysql:host=127.0.0.1;port=3306;dbname=test', 'username', 'password');</code>
If you want to connect via a Unix socket, you can specify the path to the socket like so:
<code class="php">new PDO('mysql:unix_socket=/tmp/mysql.sock;dbname=test', 'username', 'password');</code>
You can also modify the pdo_mysql.default_socket configuration in your php.ini file to set the default Unix socket location.
The above is the detailed content of Why am I getting \'No such file or directory\' error when connecting to MySQL via PDO?. For more information, please follow other related articles on the PHP Chinese website!