access is denied for user 'root'@localhost mysql error 1045

Gnanendra picture Gnanendra · Apr 5, 2011 · Viewed 8.9k times · Source

I am new to PHP. I get the following error when executing my application:

In phpMyadmin the code is like this

$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;

As I have taken back up, I have change the above code to

$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'Pass123';
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;

Now I am get the following error

Access denied for user 'root'@'localhost' (using password: YES) MySQL Error # :1045

Please let me know, what went wrong here.

Answer

Cees Timmerman picture Cees Timmerman · Mar 26, 2013

After wasting most of a day on this problem, it turned out that all i had to do was supply the non-localhost hostname. I've no idea why (the user is allowed to connect from Any host), but it works!

root@base:~# mysql -u username -h hostname -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.

And in PHP:

Test 1807:
<?php
$username = "username";
$password = "password";
$hostname = "actualhostnamenotlocalhost"; 

$con = mysqli_connect($hostname, $username, $password);

// Check connection
if (mysqli_connect_errno($con)){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_close($con);    

?>
OK.