What are best practices for handling special characters in dynamic data extracted from databases in PHP applications?

Special characters in dynamic data extracted from databases can cause security vulnerabilities such as SQL injection attacks or display issues on the front end. To handle special characters safely in PHP applications, it is important to use parameterized queries when interacting with the database, sanitize input data before processing or displaying it, and properly encode output to prevent cross-site scripting attacks.

// Example of using parameterized queries to handle special characters safely
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll();

// Example of sanitizing input data before processing or displaying it
$username = htmlspecialchars($_POST['username'], ENT_QUOTES, 'UTF-8');

// Example of encoding output to prevent cross-site scripting attacks
echo htmlentities($output, ENT_QUOTES, 'UTF-8');