PHP错误:SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client

使用PHP连接MySQL 8的时候,可能会发生如标题所示的错误:

SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client
[ 2024-02-04T13:35:31+08:00 ] 192.168.56.1 GET www.hd.com/
[ error ] [2054]SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client[/home/wwwroot/www/hd/thinkphp/library/think/db/Connection.php:295]

PHP错误:SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client_第1张图片发生这种错误,是由于MySQL 8默认使用了新的密码验证插件:caching_sha2_password,而之前的PHP版本中所带的mysqlnd无法支持这种验证。解决这个问题,有两种办法。

1.一种办法是升级PHP支持MySQL 8的新验证插件

PHP 7.2.8和PHP 7.1.20已经可以支持caching_sha2_password,直接连接MySQL 8。

截止PHP 7.0.31和PHP 5.6.37还无法支持caching_sha2_password,不知道后续版本是否会做出支持。

可以通过phpinfo()函数了解当前安装的PHP是否支持caching_sha2_password:

2.在MySQL 8中创建(或修改)账户

如果不能升级PHP,可以在MySQL 8中创建(或修改)使用caching_sha2_password插件的账户,使之使用mysql_native_password,这样先前版本的PHP就可以连接使用了。

  1. 在CREATE USER时,使用IDENTIFIED WITH xxx_plugin BY ‘password‘,比如:
    CREATE USER ‘native‘@‘localhost‘ IDENTIFIED WITH mysql_native_password BY ‘password!2#4‘;
  2. 使用ALTER USER修改已有账户的验证插件:
    ALTER USER ‘native‘@‘localhost‘ IDENTIFIED WITH mysql_native_password

    ALTER USER ‘native‘@‘localhost‘ IDENTIFIED WITH mysql_native_password BY ‘new_password‘;

    采用前一种方式,账户的密码将被清除;BY子句将为账户设置新的密码。

我的操作:


mysql> use mysql ;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select host,user from user;
+-----------+------------------+
| host      | user             |
+-----------+------------------+
| %         | crm              |
| localhost | mysql.infoschema |
| localhost | mysql.session    |
| localhost | mysql.sys        |
| localhost | root             |
+-----------+------------------+
5 rows in set (0.00 sec)

mysql> ALTER USER ‘crm‘@‘%‘ IDENTIFIED WITH mysql_native_password BY ‘Hdcrm@123456‘;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%‘ IDENTIFIED WITH mysql_native_password BY ‘Hdcrm@123456‘' at line 1
mysql> ALTER USER 'crm'@'%' IDENTIFIED WITH mysql_native_password BY 'Hdcrm@123456';
Query OK, 0 rows affected (0.03 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.02 sec)

  1. /etc/my.cnf配置文件中,有一行:
    # default-authentication-plugin=mysql_native_password

    请删除注释符号“#”并重新启动mysqld使之生效,此后创建的账户均默认使用mysql_native_password。

  2. 如果您完成MySQL Server的安装之后,在没有启动过mysqld服务的情况下修改/etc/my.cnf配置,那么启动mysqld之后创建的‘root‘@‘localhost‘账户也是使用mysql_native_password插件的。

参考:https://www.cnblogs.com/zmdComeOn/p/12850498.html

你可能感兴趣的:(php,开发语言)