What are the best practices for handling special characters and umlauts in PHP when writing to and reading from a database?

Special characters and umlauts can cause issues when writing to and reading from a database if the proper character encoding is not set. To handle special characters and umlauts correctly in PHP, it is important to set the character encoding to UTF-8 both when writing data to the database and when reading data from the database.

// Set the character encoding to UTF-8 when connecting to the database
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

// When inserting data into the database, set the character set to UTF-8
$stmt = $pdo->prepare("INSERT INTO my_table (column_name) VALUES (:value)");
$stmt->bindParam(':value', $value, PDO::PARAM_STR);
$value = 'Special characters and umlauts: äöü';

// When reading data from the database, set the character set to UTF-8
$stmt = $pdo->query("SELECT column_name FROM my_table");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $stmt->fetch()) {
    echo $row['column_name'];
}