Home >Database >Mysql Tutorial >Why Does My PHP Code Get 'Access Denied' When Connecting to MySQL, and How Can I Fix It?
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:
Log in to MySQL as the root user using:
mysql -u root -p -h localhost
Create a new user with the desired credentials:
CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'new_password';
Create the database to be used:
CREATE DATABASE database_name;
Grant privileges to the new user for the database:
GRANT ALL PRIVILEGES ON database_name.* TO 'new_user'@'localhost';
Log out of the root account and log in as the new user:
quit; mysql -u new_user -p -h localhost
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!