What are some potential pitfalls when dealing with character encoding in PHP, specifically when storing data in a MySQL database and sending emails?

One potential pitfall when dealing with character encoding in PHP is mismatched character sets between the PHP script, MySQL database, and email content. To ensure proper encoding, it is important to set the character set consistently across all components. This can be achieved by specifying the character set in the connection to the MySQL database, setting the content type in the email headers, and using functions like utf8_encode() or utf8_decode() to handle encoding and decoding of strings.

// Set character set for MySQL connection
$mysqli = new mysqli("localhost", "username", "password", "database");
$mysqli->set_charset("utf8");

// Set character set for email content
$headers = "Content-type: text/html; charset=utf-8\r\n";

// Encode or decode strings as needed
$encodedString = utf8_encode($originalString);
$decodedString = utf8_decode($encodedString);