SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

lamka02sk picture lamka02sk · Apr 26, 2016 · Viewed 241.9k times · Source

I just installed Ubuntu 16.04 and installed web server on it. Everything works well, but I cannot access database. Even if I create new user and grant all privileges, I can't create database In PHP I'm getting this error:

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

When I try to login in terminal, it works, but in PHP and phpmyadmin don't.

PHP Code:

protected $host = '127.0.0.1';
protected $db = 'dbname';
protected $name = 'root';
protected $pass = 'root';
protected $conn;
private static $settings = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
);

public function __construct() {
    try {
        $this->conn = new PDO("mysql:host=$this->host;dbname=$this->db", $this->name, $this->pass, self::$settings);
    } catch (PDOException $e) {
        echo $e->getMessage();
    }
}

Answer

Andris picture Andris · Apr 28, 2016

Turns out you can't use the root user in 5.7 anymore without becoming a sudoer. That means you can't just run mysql -u root anymore and have to do sudo mysql -u root instead.

That also means that it will no longer work if you're using the root user in a GUI (or supposedly any non-command line application). To make it work you'll have to create a new user with the required privileges and use that instead.

See this answer for more details.