What are some best practices for handling special characters and HTML code in PHP when interacting with a database?

Special characters and HTML code can cause issues when interacting with a database in PHP, as they can lead to SQL injection attacks or unexpected behavior. To handle special characters and HTML code properly, it is important to sanitize input data before inserting it into the database. This can be done using functions like htmlspecialchars() to escape special characters and prevent HTML injection attacks.

// Sanitize input data before inserting into the database
$unsafe_data = "<script>alert('XSS attack');</script>";
$safe_data = htmlspecialchars($unsafe_data);

// Insert sanitized data into the database
$query = "INSERT INTO table_name (column_name) VALUES ('$safe_data')";
// Execute the query using your database connection