What are the recommended methods for handling character encoding and displaying special characters in PHP scripts when working with databases?

When working with databases in PHP, it is important to ensure that character encoding is properly handled to display special characters correctly. One recommended method is to set the character encoding for the database connection using functions like mysqli_set_charset or PDO::exec. Additionally, using htmlspecialchars or htmlentities functions when outputting data from the database can help prevent XSS attacks and ensure special characters are displayed correctly.

// Set character encoding for the database connection
mysqli_set_charset($connection, 'utf8');

// Query the database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Display data with special characters
while ($row = mysqli_fetch_assoc($result)) {
    echo htmlspecialchars($row['column_name']);
}