What are some best practices for handling database connections and queries in PHP to avoid errors like "Access denied for user"?

When handling database connections and queries in PHP, it is important to ensure that the database credentials are correct and that the user has the necessary permissions to access the database. To avoid errors like "Access denied for user", make sure to double-check the username, password, host, and database name in your connection settings.

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$database = "mydatabase";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

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