php无法连接mysql8.x

问题描述

php使用mysqli_real_connect链接数据出现

Warning: mysqli_real_connect(): The server requested authentication method unknown to the client [caching_sha2_password] in D:\php\test.php on line 8

Warning: mysqli_real_connect(): (HY000/2054): The server requested authentication method unknown to the client in D:\php\test.php on line 8
error
=============Connect Error: The server requested authentication method unknown to the client

问题出现的环境背景及自己尝试过哪些方法

出现的环境信息mysql 8.0.13; php 7.2.0; window8;

以下两个方案都不行

试过的方案一:

CREATE USER 'aaa'@'localhost'
IDENTIFIED WITH mysql_native_password BY 'password';
# 还有
ALTER USER 'aaa'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;
ALTER USER 'aaa'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
FLUSH PRIVILEGES;
方案二:
参考https://segmentfault.com/q/10...

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)
php代码

<?php
$con=mysqli_init();
if (!$con)
{
    die("mysqli_init failed");
}

if (!mysqli_real_connect($con,"localhost","aaa","password","wp"))
{
   echo "error<br/>=============";
    die("Connect Error: " . mysqli_connect_error());
}

mysqli_close($con);
?>

你期待的结果是什么?实际看到的错误信息又是什么?

能够正确连接数据库

阅读 5.1k
3 个回答

mysql8用了新的加密,你应该修改mysql配置,改成旧的加密,然后重启mysql

首先,default_authentication_plugin=mysql_native_password
然后,ALTER USER 'aaa'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'

新手上路,请多包涵

直接给你贴官方文档吧!所以一定会要经常关注官方文档!
使用 PHP 7.1.16 之前的版本或者 PHP 7.2(PHP 7.2.4 之前的版本), 需要将 MySQL 服务器的默认密码插件设置为:mysql_native_password。 否则,当你连接的时候就会看到类似这样的错误: The server requested authentication method unknown to the client [caching_sha2_password]。 即使你未使用 caching_sha2_password 也会这样。

发生这种错误的原因是,MySQL 8 服务器默认会使用 caching_sha2_password 扩展, 老版本的 PHP 驱动(mysqlnd)无法识别这个扩展。 所以需要在 MySQL 的配置文件 my.cnf 中,设置 default_authentication_plugin=mysql_native_password。 在后续的 PHP 发行版本中,会提供对 MySQL caching_sha2_password 扩展的支持。 目前只有 mysql_xdevapi 扩展是 支持 MySQL 的 caching_sha2_password 扩展的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题