Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 765
Dannyboy Avatar asked Jul 27 '15 17:07

Dannyboy


People also ask

Should I use utf8 or 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.

What is the difference between utf8mb4 and utf8 charsets in MySQL?

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 .

What is charset 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.


1 Answers

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'); 
like image 116
Nick Avatar answered Nov 15 '22 10:11

Nick