📌  相关文章
📜  php catch mysqli_connect(): (HY000 1045): Access denied - PHP Code Example(1)

📅  最后修改于: 2023-12-03 15:18:19.501000             🧑  作者: Mango

PHP Catch mysqli_connect() Error

When developing PHP applications that connect to a MySQL database, you may come across an error message that reads:

mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

This error is commonly caused by incorrect database connection credentials.

To troubleshoot and fix this error, you can follow these steps:

  1. Check your credentials: Ensure that the username, password, and hostname for your database are correct. You can view these details from your hosting control panel or from your PHP code if you have stored them there.

  2. Check your connection method: Ensure that you are using the correct MySQL connection method in your PHP code. The most common methods are mysqli and PDO, but you should check your database documentation for the recommended method.

  3. Check your privileges: Ensure that the user account you are using to connect to the database has the necessary permissions to read, write, and execute queries.

Here is an example PHP code snippet that catches the mysqli_connect() error:

<?php
$servername = "localhost";
$username = "root";
$password = "wrongpassword"; // incorrect password
$dbname = "example_database";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

In this example, we intentionally used the wrong password to trigger the error message. The code catches the error using the die() function and displays a personalized error message.

In summary, catching and fixing the mysqli_connect() error requires you to check your connection credentials, connection method, and user privileges. By following these steps, you should be able to troubleshoot and fix the error with ease.