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
Release: 2024-12-11 18:32:12
Original
650 people have browsed it

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
    Copy after login
  2. Create a new user with the desired credentials:

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

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

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

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

    source database_schema.sql;
    Copy after login

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");
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template