Home >Database >Mysql Tutorial >Why Does My PHP Script Get 'Connect failed: Access denied' Even Though I Can Access the MySQL Database Elsewhere?

Why Does My PHP Script Get 'Connect failed: Access denied' Even Though I Can Access the MySQL Database Elsewhere?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 10:37:16609browse

Why Does My PHP Script Get

Issues with Database Connectivity: "Connect failed: Access denied for user 'root'" in PHP Function

When attempting to interact with a MySQL database using a PHP script, you may encounter the error:

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)"

Despite having the correct password, you can successfully access the database using the command line or through XAMPP, and the function seems to work on your local PC.

Resolving the Issue

To rectify this problem, consider the following steps:

  1. Create a Dedicated User: Instead of using the "root" user by default, create a new user with restricted privileges for your database.
  2. Assign Database Privileges: Grant the necessary privileges (typically ALL PRIVILEGES) to the new user for the specific database you want to connect to.
  3. Recreate the Database: Recreate your database using an SQL script or a tool to ensure there are no lingering issues.
  4. Use the Newly Created User: In your PHP script, establish the connection using the new username and password.
  5. Example Query:

    $conn = new mysqli("localhost", "francesco", "some_pass", "shop");

By following these steps, you should be able to successfully connect to your database from PHP using the newly created user and avoid the "Connect failed: Access denied" error.

The above is the detailed content of Why Does My PHP Script Get 'Connect failed: Access denied' Even Though I Can Access the MySQL Database Elsewhere?. 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