近日在安裝LAMP環境時訪問本地MYSQL數據庫錯誤
錯誤如下:
Warning: mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server
問題描述:
由于將安裝mysql服務器文件位置修改在home目錄下,造成本地訪問問題。
在網上找了很久終于找到解決問題的方法:
1、先確保在本機上使用命令能登陸,如果也出現提示sock文件位置問題,那么需要修改mysql配置文件(/etc/my.cnf)
增加如下配置:
[mysql]
socket=/home/mysqldata/mysql.sock#這是我的sock文件的位置
2、php使用mysqli無法訪問問題
解決方法:
找到PHP配置文件(/etc/php.ini)找到mysqli.default_socket這個值
修改為mysqli.default_socket =/home/mysqldata/mysql.sock#這是我的sock文件的位置
問題分析(這是我在網上找到的解決方案):
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.
其實就是說UNIX系統需要將localhost 這個地址進行轉換的文件
解決的方法其他有三個
There are a few ways to solve this problem.
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.
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
.
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')
1、修改連接文件中localhost 為127.0.0.1
2、查看my.cnf文件中sock
文件的位子,并賦值到
php.ini
:文件中的mysqli.default_socket去
3、PHP語言直接多一個參數指向sock文件位置。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。