What are some best practices for ensuring compatibility and proper usage of database functions in PHP?

To ensure compatibility and proper usage of database functions in PHP, it is important to use prepared statements to prevent SQL injection attacks, properly handle errors to avoid potential security vulnerabilities, and close database connections when they are no longer needed to optimize performance.

// Example of using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(['username' => $username]);
$results = $stmt->fetchAll();

// Example of handling errors when executing queries
if (!$results) {
    die("Error executing query: " . $stmt->errorInfo());
}

// Example of closing a database connection when it is no longer needed
$pdo = null;