How can one optimize the code provided to prevent it from malfunctioning in PHP?

The issue with the provided code is that it does not properly handle errors that may occur during the execution of the SQL query. To prevent the code from malfunctioning, we should use error handling techniques such as try-catch blocks to catch any exceptions that may be thrown.

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();

    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    echo json_encode($result);
} catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}