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.
If you need a database, don't use MySQL or MariaDB. Use PostgreSQL. If you need to use MySQL or MariaDB, never use “utf8”. Always use “utf8mb4” when you want UTF-8.
utf-8 can store only 1, 2 or 3 bytes characters, while utf8mb4 can store 4 bytes characters as well. utf-8 is a subset of characters given by utf8mb4 .
utf8mb4 : A UTF-8 encoding of the Unicode character set using one to four bytes per character. utf8mb3 : A UTF-8 encoding of the Unicode character set using one to three bytes per character. This character set is deprecated in MySQL 8.0, and you should use utfmb4 instead.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With