Are there specific functions or methods in PHP that should be used to set the character encoding for database connections?
To set the character encoding for database connections in PHP, you should use the `set_charset()` method for MySQLi connections or the `setAttribute()` method for PDO connections. These functions allow you to specify the character encoding for the database connection, ensuring that data is stored and retrieved correctly.
// For MySQLi connections
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
}
$mysqli->set_charset('utf8');
// For PDO connections
$dsn = 'mysql:host=localhost;dbname=database';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}