What are some best practices for handling character encoding and special characters in PHP scripts that interact with databases?

When working with databases in PHP, it is essential to handle character encoding properly to prevent issues with special characters. One best practice is to set the character encoding for the database connection to match the encoding used in the PHP script. This can be done using the `set_charset()` method for MySQLi or `setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8')` for PDO.

// For MySQLi
$mysqli = new mysqli("localhost", "username", "password", "database");
$mysqli->set_charset("utf8");

// For PDO
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");
$pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');