What methods can be used in PHP to set the character encoding for database connections to prevent data corruption or display issues?
When working with databases in PHP, it is important to set the character encoding for database connections to prevent data corruption or display issues, especially when dealing with multilingual data. One common method to ensure the correct character encoding is to set the charset when establishing the database connection using PHP's PDO or mysqli extension.
// Using PDO extension
$dsn = 'mysql:host=localhost;dbname=mydatabase;charset=utf8';
$username = 'username';
$password = 'password';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
// Using mysqli extension
$mysqli = new mysqli('localhost', 'username', 'password', 'mydatabase');
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
}
$mysqli->set_charset('utf8');