The before code directly inserts user input into SQL queries and HTML, allowing attackers to inject malicious code. The after code uses parameterized queries to separate data from code in SQL, and escapes HTML special characters to prevent script execution in the browser.
Before (vulnerable to SQL injection):
user_id = input("Enter user ID:")
query = f"SELECT * FROM users WHERE id = {user_id}"
cursor.execute(query)
After (using parameterized queries):
user_id = input("Enter user ID:")
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))
Before (vulnerable to XSS):
comment = request.GET.get('comment')
html = f"<div>{comment}</div>"
return html
After (using sanitization and encoding):
import html
comment = request.GET.get('comment')
safe_comment = html.escape(comment)
html = f"<div>{safe_comment}</div>"
return html