php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

Guti_Haz picture Guti_Haz · Apr 25, 2018 · Viewed 160.2k times · Source

I am using php mysqli_connect for login to a MySQL database (all on localhost)

<?php
//DEFINE ('DB_USER', 'user2');
//DEFINE ('DB_PASSWORD', 'pass2');
DEFINE ('DB_USER', 'user1');
DEFINE ('DB_PASSWORD', 'pass1');
DEFINE ('DB_HOST', '127.0.0.1');
DEFINE ('DB_NAME', 'dbname');

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if(!$dbc){
    die('error connecting to database');    
}
?>

this is the mysql.user table: mysql.user table

MySQL Server ini File:

[mysqld]
# The default authentication plugin to be used when connecting to the server
default_authentication_plugin=caching_sha2_password
#default_authentication_plugin=mysql_native_password

with caching_sha2_password in the MySQL Server ini file, it's not possible at all to login with user1 or user2;

error: mysqli_connect(): The server requested authentication method unknown to the client [caching_sha2_password] in...

with mysql_native_password in the MySQL Server ini file, it's possible to login with user1, but with user2, same error;


how can I login using caching_sha2_password on the mySql Server?

Answer

黃皓哲 picture 黃皓哲 · Jun 9, 2018

I solve this by SQL command:

ALTER USER 'mysqlUsername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysqlUsernamePassword';

which is referenced by https://dev.mysql.com/doc/refman/8.0/en/alter-user.html

if you are creating new user

 CREATE USER 'jeffrey'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

which is referenced by https://dev.mysql.com/doc/refman/8.0/en/create-user.html

this works for me