Home >Database >Mysql Tutorial >Why am I getting \'No such file or directory\' error when connecting to MySQL via PDO?

Why am I getting \'No such file or directory\' error when connecting to MySQL via PDO?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 18:17:31647browse

Why am I getting

Error: "No such file or directory" 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.

Resolution

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn