Encounters with the "SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'" error after setting up an Ubuntu web server can be frustrating. While database access may seem accessible through the terminal, errors in PHP and phpMyAdmin persist. Understanding the underlying cause is crucial for resolving this issue.
Root User Restrictions
MySQL 5.7 onwards introduces restrictions on the root user. Without elevated privileges, direct access to MySQL using mysql -u root is no longer possible. Instead, sudo mysql -u root is required, prompting a password entry.
This restriction extends to GUI and non-command line applications. To alleviate this issue, create a new user with the necessary privileges instead of using the root user.
Implementation in PHP
In the provided PHP code, login credentials are hardcoded. To bypass root user restrictions, modify the __construct() method to incorporate a new user with appropriate permissions:
<code class="php">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(); } }</code>
Replace $this->name and $this->pass with the newly created user's credentials. Ensure that the user possesses the necessary privileges to access the database.
Additional Resources
For further insights and troubleshooting steps, refer to the following resource:
The above is the detailed content of Why Can\'t I Access My MySQL Database as Root User in Ubuntu?. For more information, please follow other related articles on the PHP Chinese website!