Home >Database >Mysql Tutorial >How to Fix 'Connect failed: Access denied' MySQL Errors in PHP?

How to Fix 'Connect failed: Access denied' MySQL Errors in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 00:05:10508browse

How to Fix

"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:

  1. 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';
  2. 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';
  3. Reload Database: Reload the MySQL database to ensure the changes take effect:

    FLUSH PRIVILEGES;
  4. 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");
  5. Troubleshooting: If the error persists, double-check the user privileges, the hostname (localhost or the actual IP address), and the database name. Additionally, ensure that the MySQL server is running and listening for connections on the correct port (typically 3306).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn