How can the code be refactored to utilize PDO for database interactions instead of mysql_ functions?

The issue can be solved by refactoring the code to use PDO (PHP Data Objects) for database interactions instead of the deprecated mysql_ functions. PDO provides a more secure and flexible way to interact with databases in PHP.

<?php
// Connect to the database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

// Prepare and execute a query using PDO
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$user = $stmt->fetch();

// Use the retrieved data
echo $user['username'];

// Close the PDO connection
$pdo = null;
?>