What are common issues with UTF-8 encoding and PHP when retrieving data from a database?
Common issues with UTF-8 encoding and PHP when retrieving data from a database include garbled or incorrectly displayed characters due to mismatched character sets. To solve this, ensure that your database, table, and column are all set to use UTF-8 encoding. Additionally, make sure to set the connection charset to UTF-8 when connecting to the database in your PHP code.
// Set UTF-8 encoding for database connection
$dsn = 'mysql:host=localhost;dbname=mydatabase;charset=utf8';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->exec("set names utf8");
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}