Verification: a143cc29221c9be0

Pdo php set names utf8

Specifying character set in the dsn string

To get UTF-8 charset you can specify that in the DSN:

$dsn = 'mysql:host=localhost; dbname=test; charset=UTF8';

$dbh = new PDO($dsn, $user, $password);

Specifying character set by executing SET NAMES utf8

Prior to PHP 5.3.6, the charset option was ignored. For older version use following method:

//For PHP version earlier to 5.3.6)
$dbh = new PDO($dsn, $user, $password);
$dbh->exec('set names utf8');

If you also need to set collation:

$dbh->exec('set names utf8 COLLATE collateName');

//For utf8 the default collation is utf8_general_ci
$dbh->exec('set names utf8 COLLATE utf8mb4_unicode_ci');

Specifying character set in PDO constructor’s fourth parameter

You also can set the character encoding by creating an options-array for PDO constructor’s fourth parameter:

//For PHP version prior to 5.3.6)
$options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'];

$db = new PDO($dsn, $user, $password, $options);

Note: The above example only works with MySQL database.