When the host is filled in as localhost, MySQL will use the unix domain socket connection, and when the host is filled in as 127.0.0.1, MySQL will use the TCP/IP connection. Connections using Unix sockets are faster and more secure than TCP/IP connections. This is a feature of MySQL connections.
When using localhost, sometimes there is a connection error, this problem has the following solutions:
- Use TCP/IP instead of Unix sockets. That is, when connecting, replace localhost with 127.0.0.1.
-
Modify the MySQL configuration file my.cnf and specify the location of mysql.socket:
/var/lib/mysql/mysql.sock (your mysql.socket path).
-
Specify the location of my.socket directly when php establishes a connection (official document: mysqli_connect ). for example:
$db = new MySQLi('localhost', 'root', 'root', 'my_db', '3306', '/var/run/mysqld/mysqld.sock')