Home > Database > Mysql Tutorial > Why Does My PHP Code Get 'Access Denied' Connecting to MySQL, Even Though the Root User Works?

Why Does My PHP Code Get 'Access Denied' Connecting to MySQL, Even Though the Root User Works?

Mary-Kate Olsen
Release: 2024-12-31 08:49:13
Original
354 people have browsed it

Why Does My PHP Code Get

Resolving "Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" Error in PHP Function

When connecting to a MySQL database using PHP, users may encounter the "Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" error. This issue can arise despite correctly setting the password and accessing the database from the command line.

Solution

To solve this problem, the following steps can be taken:

  1. Log in as Root User:

    • Log in to MySQL as the root user using mysql -u root -p -h localhost.
  2. Create a New User:

    • Create a new user with limited privileges. For example: CREATE USER 'francesco'@'localhost' IDENTIFIED BY 'some_pass';
  3. Create the Database:

    • Create the database for the user. For instance: CREATE DATABASE shop;
  4. Grant Privileges:

    • Grant the new user privileges for the database. For example: GRANT ALL PRIVILEGES ON shop.* TO 'francesco'@'localhost';
  5. Log Out and Back In:

    • Log out of the root account and back into the new user account. Use quit; to log out and mysql -u francesco -p -h localhost to log in as the new user.
  6. Rebuild the Database:

    • Rebuild the database using a script, such as source shop.sql.
  7. Connect in PHP:

    • In the PHP function, use the new user credentials to connect to the database. Example: $conn = new mysqli("localhost", "francesco", "some_pass", "shop");

By following these steps, the connection to the MySQL database from the PHP function should resolve the access denied issue.

The above is the detailed content of Why Does My PHP Code Get 'Access Denied' Connecting to MySQL, Even Though the Root User Works?. 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