What are some common pitfalls to avoid when handling MySQL queries within PHP classes?

One common pitfall to avoid when handling MySQL queries within PHP classes is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely pass user input to the database.

// Example of using prepared statements with parameterized queries to avoid SQL injection

// Assume $mysqli is a mysqli object connected to the database

class User {
    private $mysqli;

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

    public function getUserById($userId) {
        $stmt = $this->mysqli->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        $stmt->close();
        return $user;
    }
}

$user = new User($mysqli);
$userData = $user->getUserById($_GET['user_id']);