Home >Database >Mysql Tutorial >Why Does My PHP Code Get 'Access Denied' When Connecting to MySQL, and How Can I Fix It?

Why Does My PHP Code Get 'Access Denied' When Connecting to MySQL, and How Can I Fix It?

Linda Hamilton
Linda HamiltonOriginal
2024-12-11 18:32:12650browse

Why Does My PHP Code Get

Connecting to MySQL Database Failure from PHP: Resolving "Access Denied" Issue

Attempting to interact with a MySQL database from PHP can sometimes result in an "Access denied" error. In this instance, the specific error received is "Connect failed: Access denied for user 'root'@'localhost' (using password: YES)." Despite having access to the database through the command line and using the correct password, the webpage fails to connect.

To resolve this issue, the following steps were taken:

  1. Log in to MySQL as the root user using:

    mysql -u root -p -h localhost
  2. Create a new user with the desired credentials:

    CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'new_password';
  3. Create the database to be used:

    CREATE DATABASE database_name;
  4. Grant privileges to the new user for the database:

    GRANT ALL PRIVILEGES ON database_name.* TO 'new_user'@'localhost';
  5. Log out of the root account and log in as the new user:

    quit;
    mysql -u new_user -p -h localhost
  6. Import the database schema and data using a script:

    source database_schema.sql;

After these changes were implemented, the PHP script successfully connected to the MySQL database using the following call:

$conn = new mysqli("localhost", "new_user", "new_password", "database_name");

By following these steps, the "Access denied" error was resolved, allowing the PHP function to interact with the MySQL database.

The above is the detailed content of Why Does My PHP Code Get 'Access Denied' When Connecting to MySQL, and How Can I Fix It?. 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