Fixing PHP Database Connection Errors: Access Denied, Unknown Database & More
Fix PHP Database Connection Errors: Access Denied, Unknown Database & More
🔴 1. Access Denied for User ('HY000/1045')
Error Message:
Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)
Cause: Incorrect credentials or insufficient privileges.
Solution:
- Verify that the username, password, and database name are correct.
- Use the following SQL:
GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost' IDENTIFIED BY 'password'; FLUSH PRIVILEGES;
- Ensure the host is correct (e.g., 'localhost').
Precaution: Use strong passwords and restrict privileges.
🔵 2. Unknown Database ('HY000/1049')
Error Message:
PDOException: SQLSTATE[HY000] [1049] Unknown database 'database_name'
Cause: Database doesn’t exist.
Solution:
- Verify the database name is correct.
- Create it using:
CREATE DATABASE database_name;
- Update your config file with the correct name.
Precaution: Regularly backup your databases.
⚠️ 3. No Such File or Directory ('HY000/2002')
Error Message:
Warning: mysqli::real_connect(): (HY000/2002): No such file or directory
Cause: MySQL is not running or socket path is wrong.
Solution:
- Start the MySQL server.
- Check
my.cnf
for socket path. - Update PHP config:
mysqli.default_socket = /path/to/mysql.sock
- Use
127.0.0.1
instead oflocalhost
.
Precaution: Monitor MySQL server health regularly.
🔧 Best Practices
- Use environment variables for DB credentials.
- Handle errors using
try-catch
blocks. - Limit user privileges.
- Schedule backups regularly.
❓ Frequently Asked Questions (FAQ)
Q1: How to test my database connection?
A:
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
echo 'Connected successfully';
?>
Q2: Why use 127.0.0.1 instead of localhost?
A: It forces TCP/IP instead of using a socket file, avoiding some server issues.
Q3: What if I forget my DB password?
A: Reset using MySQL:
SET PASSWORD FOR 'user'@'localhost' = PASSWORD('newpass');
Comments
Post a Comment