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

To avoid errors like "Access denied" when handling database connections and queries in PHP scripts, it is important to ensure that the database credentials are correct and properly secured. Additionally, using prepared statements can help prevent SQL injection attacks and improve the overall security of the application.

<?php
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

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

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

// Example query using prepared statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = "example_username";
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // Process results
}

$stmt->close();
$conn->close();
?>