What are the best practices for handling database connections and prepared statements in PHP scripts?

When handling database connections and prepared statements in PHP scripts, it is important to establish a secure and efficient connection to the database and use prepared statements to prevent SQL injection attacks. To achieve this, you should create a separate file to store database connection details, establish the connection using PDO or MySQLi, and use prepared statements to execute queries safely.

// Database connection details
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';

// Create a PDO connection
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Use prepared statements to execute queries safely
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);