What are the potential pitfalls of directly using PDO in business logic?

Using PDO directly in business logic can lead to tightly coupling database operations with application logic, making it harder to maintain and test code. To solve this issue, it's recommended to separate database operations into a separate data access layer or repository pattern. This helps in keeping the business logic independent of the database implementation, improving code readability and maintainability.

// Example of separating database operations into a data access layer

class UserRepository {
    private $pdo;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }

    public function getUserById($userId) {
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = :id");
        $stmt->bindParam(':id', $userId);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Add more methods for other database operations
}

// Implementation in business logic
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$userRepository = new UserRepository($pdo);

$user = $userRepository->getUserById(1);