Can't Connect to MySQL Server through Socket: Troubleshooting
When connecting to a MySQL database using PHP's mysqli class, you may encounter the error "Can't connect to local MySQL server through socket 'MySQL' (2)." This indicates that the MySQL client library is attempting to connect via a Unix domain socket rather than a TCP/IP connection.
Unix Domain Socket vs. TCP/IP Connection
By default, the MySQL client library uses a Unix domain socket when connecting to localhost. This is a faster and more secure connection method, but it can only be used with localhost. To connect to MySQL using TCP/IP instead, specify 127.0.0.1 as the host name or use the --protocol=TCP option.
Solutions to the Error
There are several ways to resolve this error:
$db = new MySQLi('localhost', 'kamil', '***', '', 0, '/var/run/mysqld/mysqld.sock')
The above is the detailed content of Why Can't My PHP Code Connect to the MySQL Server via Socket?. For more information, please follow other related articles on the PHP Chinese website!