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:

  1. Verify that the username, password, and database name are correct.
  2. Use the following SQL:
    GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost' IDENTIFIED BY 'password';
    FLUSH PRIVILEGES;
  3. 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:

  1. Verify the database name is correct.
  2. Create it using:
    CREATE DATABASE database_name;
  3. 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:

  1. Start the MySQL server.
  2. Check my.cnf for socket path.
  3. Update PHP config:
    mysqli.default_socket = /path/to/mysql.sock
  4. Use 127.0.0.1 instead of localhost.

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

Popular posts from this blog

PolicePAD Bandobast & Duty Allocation Software for Smart Policing

How to Build a RESTful API Using PHP 8 and Slim Framework [2025 Guide]

Mastering CSS: Ultimate Guide to Selectors, Properties & Values for Web Design in 2025