警告: mysqli_connect() : (HY000/2002) : 没有这样的文件或目录

我正在尝试在我的 Mac 上安装普通的论坛,为此我刚刚从 MySQL 命令行创建了一个数据库和一个用户:

mysql> CREATE DATABASE vanilla;
Query OK, 1 row affected (0.00 sec)


mysql> create user 'vanilla_user3'@'localhost' IDENTIFIED BY 'vanilla_password';
Query OK, 0 rows affected (0.00 sec)


mysql> GRANT ALL PRIVILEGES ON * . * TO 'vanilla_user3'@'localhost';
Query OK, 0 rows affected (0.00 sec)


mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

因此,我尝试使用以下代码进行连接:

$con=mysqli_connect("localhost","vanilla_user3","vanilla_password","vanilla");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

但不幸的是,我得到了一个错误的说法

警告: mysqli _ connect () : (HY000/2002) : 第3行的/Users/kramer65/Sites/橡皮图章/info.php 中没有这样的文件或目录 未能连接到 MySQL: 没有这样的文件或目录

知道我哪里做错了吗?

119092 次浏览

Alright, I just found the solution. The problem turned out to be that the host shouldn't have been localhost, but 127.0.0.1. I always thought localhost and 127.0.0.1 was the same, but it turned out to be different.

So maybe as a tip for future users, always use the ip when in doubt.

I had the same problem but the issue was something related to php.ini file.

I had to edit these two lines in /etc/php.ini (or wherever your php.ini is located):

mysql.default_socket = /tmp/mysql.sock
mysqli.default_socket = /tmp/mysql.sock

Restart apache server to make sure the changes are reflected.

sudo apachectl restart

Let's say your MAMP MySQL Port is set to 8889 like it is by default. Sometimes localhost alone is not enough in which case you have to put the MySQL port in there too so you would do localhost:8889 or localhost:{whatever your MySQL port number is}. I'm still new to MySQL so I don't know the reason why, but to anyone out there who recently got the message: Warning: mysqli::mysqli(): (HY000/2002): No such file or directory in ... adding the MySQL port number onto localhost was the fix for me.

set port in host:

$con = mysqli_connect("localhost:**3306**","vanilla_user3","vanilla_password","vanilla");

If using docker use the mysql container name as host name of mysql. For example if this is the docker compose file:

mysqldb:
image: mysql:5.7.22
container_name: mysqlHost
ports:
- "33099:3306"

Host name will be mysqlHost and port will be 3306 and not 33099!

If you are not using docker compose, docker ps reveals the running container names.

find php.ini file in /opt/lampp/etc/ then edit:

mysql.default_socket = /tmp/mysql.sock
mysqli.default_socket = /tmp/mysql.sock

after this in your DB connect file change from localhost to 127.0.0.1. everything will be ok. however, if you attempted the config.inc.php file, make sure its all set to 127.0.0.1, not localhost.