MySQLi::MySQLi(): (Hy000/2002): Can't Connect to Local MySQL Server Through Socket 'MySQL' (2)

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

When you use just "localhost" the MySQL client library tries to use a Unix domain socket for the connection instead of a TCP/IP connection. The error is telling you that the socket, called MySQL, cannot be used to make the connection, probably because it does not exist (error number 2).

From the MySQL Documentation:

On Unix, MySQL programs treat the host name localhost specially, in a
way that is likely different from what you expect compared to other
network-based programs. For connections to localhost, MySQL programs
attempt to connect to the local server by using a Unix socket file.
This occurs even if a --port or -P option is given to specify a port
number. To ensure that the client makes a TCP/IP connection to the
local server, use --host or -h to specify a host name value of
127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by
using the --protocol=TCP option.

There are a few ways to solve this problem.

  1. You can just use TCP/IP instead of the Unix socket. You would do this by using 127.0.0.1 instead of localhost when you connect. The Unix socket might by faster and safer to use, though.
  2. You can change the socket in php.ini: open the MySQL configuration file my.cnf to find where MySQL creates the socket, and set PHP's mysqli.default_socket to that path. On my system it's /var/run/mysqld/mysqld.sock.
  3. Configure the socket directly in the PHP script when opening the connection. For example:

    $db = new MySQLi('localhost', 'kamil', '***', '', 0, 
    '/var/run/mysqld/mysqld.sock')

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Are you connecting to "localhost" or "127.0.0.1" ? I noticed that when you connect to "localhost" the socket connector is used, but when you connect to "127.0.0.1" the TCP/IP connector is used. You could try using "127.0.0.1" if the socket connector is not enabled/working.

PHP Error mysqli::mysqli(): (HY000/2002)

Finally got the solution to this problem, I'm sharing it because I can't find a solution anywhere else. The $host should be linked to "127.0.0.1" but for an unknown reason my host only worked when it was "127.0.0.1:3307" or the name of your port for mysql at the end, don't forget the ":". PS I changed my db connection back to using the procedural way despite what the Ashu said and it worked.

MySQL connection not working: 2002 No such file or directory

If you use Linux: the path to the mysql.sock file is wrong. This is usually because you are using (LAMPP) XAMPP and it isn't in /tmp/mysql.sock

Open the php.ini file and find this line:

mysql.default_socket

And make it

mysql.default_socket = /path/to/mysql.sock


Related Topics



Leave a reply



Submit