php连接mysql报错No such file or directory

时间:2022-06-20 16:08:14

php测试文件如下:

1
2
3
4
5
6
7
8
9
10
11
<?php
$con = mysql_connect("localhost","root","zengjie2");
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}
else
{
    echo "ok";
}
?>

访问后提示:

1
2
Warning: mysql_connect(): No such file or directory in /usr/local/nginx/html/mysql.php on line 3
Could not connect: No such file or directory

解决方法:

登陆mysql

输入status,输出如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Connection id:   4
Current database:
Current user:    root@localhost
SSL:     Not in use
Current pager:   stdout
Using outfile:   ''
Using delimiter:    ;
Server version:  5.1.73 Source distribution
Protocol version:   10
Connection:  Localhost via UNIX socket
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    latin1
Conn.  characterset:    latin1
UNIX socket:     /var/lib/mysql/mysql.sock
Uptime:  14 min 29 sec

记下UNIX socket路径  /var/lib/mysql/mysql.sock

查看/tmp/mysql.sock,不存在这个文件,那么建个Link

1
2
cd /tmp
ln -s /var/lib/mysql/mysql.sock mysql.sock

重新访问php文件,成功连接。

以上是一种情况,另外一种情况: 存在/tmp/mysql.sock 但是不存在 /var/lib/mysql/mysql.sock

1
2
3
4
cd /var/lib
mkdir mysql
cd mysql
ln -s /tmp/mysql.sock mysql.sock