25

when initializing PDO - should I do: charset=UTF8 or charset=UTF8MB4 ?

here's my intialization:

$dsn = 'mysql:host=example.com;dbname=testdb;port=3306;charset=UTF8';
$dbh = new \Pdo($dsn, 'username', 'pass');
$dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            

But should dsn be this:

$dsn = 'mysql:host=example.com;dbname=testdb;port=3306;charset=UTF8MB4';

if mysql database has a default charset UTF8MB4.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Dannyboy
  • 1,963
  • 3
  • 20
  • 37

1 Answers1

53

You should use utf8mb4 for PDO and your database structures.

$dsn='mysql:host=example.com;dbname=testdb;port=3306;charset=utf8mb4';

When possible, don't forget to set the character encoding of your pages as well. PHP example:

mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
Fabien Sa
  • 9,135
  • 4
  • 37
  • 44
Nick
  • 2,573
  • 19
  • 21