<?php $USER ='root'; $PW ='pwpwpw'; $HOST ='localhost'; $mysqli = new mysqli($HOST, $USER, $PW, 'test'); if ($mysqli->connect_error) { echo $mysqli->connect_errno; echo "\n"; echo $mysqli->connect_error; echo "\n"; } else { echo "ok"; }執行後出現:
PHP Warning: mysqli::__construct(): (HY000/2002): No such file or directory in /home/web/mysql_test.php on line 6
查一下 mysql status
mysql> status
--------------
mysql Ver 8.0.22-0ubuntu0.20.04.3 for Linux on x86_64 ((Ubuntu))
Connection id: 4
Current database:
Current user: root@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 5.7.33-log Source distribution
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: utf8
Db characterset: utf8
Client characterset: utf8
Conn. characterset: utf8
UNIX socket: /tmp/mysqld.sock
Binary data as: Hexadecimal
Uptime: 46 sec
Threads: 1 Questions: 8 Slow queries: 0 Opens: 110 Flush tables: 1 Open tables: 32 Queries per second avg: 0.173
--------------
簡單解決 方法1
修改 php 中的 mysql 連接方式加上 /tmp/mysql.sock
$mysqli = new mysqli($HOST, $USER, $PW, 'test', null , '/tmp/mysql.sock');
簡單解決 方法2
修改 php.inipdo_mysql.default_socket=/tmp/mysql.sock mysql.default_socket=/tmp/mysql.sock mysqli.default_socket=/tmp/mysql.sock(要重啟 apache httpd 或 nginx)
最簡單的解決 方法3
ln -s /tmp/mysql.sock /var/lib/mysql/mysql.sock
比較好的解法
查看 phpinfo() 資料
看一下 default_socket 的路徑
問題出在 php內的 socket 路徑跟 mysql server 的 /tmp/mysqld.sock 不同
只要修改 my.ini
將 socket 改為:
[client] socket = /var/run/mysqld/mysqld.sock [mysqld] socket = /var/run/mysqld/mysqld.sock
重啟 mysqld 即可