What potential issues can arise when directly using session variables in SQL queries?

Using session variables directly in SQL queries can open up the possibility of SQL injection attacks if the session variable is not properly sanitized. To prevent this, it is important to sanitize the session variable before using it in a query by using prepared statements or parameterized queries.

// Sanitize the session variable before using it in a query
$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :userId");
$stmt->bindParam(':userId', $userId, PDO::PARAM_INT);
$stmt->execute();