Home >Database >Mysql Tutorial >How to Fix 'Connect failed: Access denied' MySQL Errors in PHP?
"Connect failed: Access denied" Error Resolved for MySQL Connection from PHP Function
When attempting to connect to a MySQL database from a PHP function, users may encounter the error message "Connect failed: Access denied for user 'root'@'localhost' (using password: YES)." This issue often arises due to insufficient user privileges or incorrect database configuration.
To resolve the problem, the following steps can be taken:
Create a New Database User: Log in as the 'root' user and create a new user with the required privileges. For example, using the command:
CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'secure_password';
Grant Permissions: Grant the necessary privileges to the new user for the specific database. In this case, it might be something like:
GRANT ALL PRIVILEGES ON database_name.* TO 'new_user'@'localhost';
Reload Database: Reload the MySQL database to ensure the changes take effect:
FLUSH PRIVILEGES;
Connect Using New User: In the PHP function, update the connection details to use the new user and password:
$conn = new mysqli("localhost", "new_user", "secure_password", "database_name");
By following these steps, users can establish a secure and authorized connection to the MySQL database from within their PHP functions.
The above is the detailed content of How to Fix 'Connect failed: Access denied' MySQL Errors in PHP?. For more information, please follow other related articles on the PHP Chinese website!