您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 如何解决Linux PHP连不上MySQL数据库问题
## 问题现象
在Linux服务器上运行PHP程序时,常会遇到无法连接MySQL数据库的情况,典型报错包括:
Warning: mysqli_connect(): (HY000/2002): Connection refused
或
Access denied for user ‘username’@‘localhost’ (using password: YES)
## 常见原因与解决方案
### 1. MySQL服务未运行
```bash
# 检查MySQL状态
systemctl status mysql
# 启动服务(根据实际服务名可能是mysqld或mariadb)
sudo systemctl start mysql
MySQL默认使用3306端口:
# 检查端口监听
netstat -tulnp | grep 3306
# 测试远程连接(替换为实际IP)
telnet 服务器IP 3306
若未监听,需检查my.cnf
配置文件中bind-address
参数:
bind-address = 0.0.0.0 # 允许所有IP连接
-- 登录MySQL后执行
GRANT ALL PRIVILEGES ON *.* TO '用户名'@'%' IDENTIFIED BY '密码';
FLUSH PRIVILEGES;
确保已安装PHP MySQL扩展:
# 根据PHP版本选择扩展
sudo apt install php-mysql # PHP7+
sudo yum install php-mysqli # CentOS
# 临时关闭SELinux
setenforce 0
# 防火墙放行3306
sudo firewall-cmd --add-port=3306/tcp --permanent
sudo firewall-cmd --reload
mysql -u用户 -p密码
<?php
$conn = new mysqli("127.0.0.1", "用户", "密码", "数据库");
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
/var/log/php_errors.log
[mysqld]
general_log = 1
general_log_file = /var/log/mysql/queries.log
sudo tcpdump -i any port 3306 -w mysql_debug.pcap
通过以上步骤,90%的连接问题都能得到解决。如仍无法连接,建议检查MySQL错误日志(通常位于/var/log/mysql/error.log
)获取具体错误信息。
“`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。