What are the best practices for handling SQL queries within a PHP class to ensure security and prevent SQL injection vulnerabilities?

To prevent SQL injection vulnerabilities when handling SQL queries within a PHP class, it is essential to use prepared statements with parameterized queries. This approach separates SQL code from user input, preventing malicious input from altering the query structure. Additionally, input validation and sanitization should be implemented to further enhance security.

class Database {
    private $conn;

    public function __construct() {
        $this->conn = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    }

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