Home >Database >Mysql Tutorial >Why Can't I Connect to My Local MySQL Server Through the Socket?
Unveiling the Connection Quandary: Understanding MySQL Socket Connection
In an attempt to establish a MySQL database connection using PHP's mysqli class, you may encounter the error: "[Can't connect to local MySQL server through socket 'MySQL' (2)]". This error arises when the MySQL client attempts to connect via a Unix domain socket on "localhost" instead of a TCP/IP connection.
Unix Socket vs. TCP/IP Connection
By default, MySQL programs on Unix systems favor Unix domain sockets over TCP/IP connections when connecting to "localhost". However, if the socket is unavailable or you specifically require a TCP/IP connection, a different method must be employed.
Resolving the Issue
Several solutions can address this issue:
1. Explicit TCP/IP Connection:
Use the IP address "127.0.0.1" or the hostname of the local server instead of "localhost" in your connection string. This forces the client to establish a TCP/IP connection.
2. Modifying PHP Configuration:
Locate the MySQL configuration file (my.cnf) and find the path where MySQL establishes the socket. Set PHP's mysqli.default_socket to this path in php.ini.
3. Explicit Socket Configuration:
Specify the socket path directly when opening the connection in the PHP script:
$db = new MySQLi('localhost', 'kamil', '***', '', 0, '/var/run/mysqld/mysqld.sock');
Conclusion
By understanding the connection mechanism used by MySQL, you can overcome this error and establish successful database connections. Remember that using a Unix domain socket may offer performance and security advantages, but explicit TCP/IP connections may be necessary in certain instances.
The above is the detailed content of Why Can't I Connect to My Local MySQL Server Through the Socket?. For more information, please follow other related articles on the PHP Chinese website!