Search code examples
mysqlpdocharacter-encoding

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


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.


Solution

  • 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');