What are the best practices for handling database connections and selections in PHP to avoid errors?

When handling database connections and selections in PHP, it's important to properly establish and close connections to avoid errors. One best practice is to use try-catch blocks to handle exceptions that may occur during database operations. Additionally, using prepared statements can help prevent SQL injection attacks and ensure data integrity.

<?php
// Establishing a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

// Using prepared statements to select data
$stmt = $conn->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$result = $stmt->fetchAll();

// Closing the database connection
$conn = null;
?>