Data Storage and Access
suggest changeThis topic specifically talks about UTF-8 and considerations for using it with a database. If you want more information about using databases in PHP, see the other database topics in this book.
Storing Data in a MySQL Database:
- Specify the
utf8mb4character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8.
MySQL will implicitly use utf8mb4 encoding if a utf8mb4_* collation is specified (without any explicit character set).
- Older versions of MySQL (< 5.5.3) do not support
utf8mb4so you’ll be forced to useutf8, which only supports a subset of Unicode characters.
Accessing Data in a MySQL Database:
- In your application code (e.g. PHP), in whatever DB access method you use, you’ll need to set the connection charset to
utf8mb4. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa. - Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection. This is usually the preferred approach.
With PDO, specify the character set in the DSN when the connection is created:
$pdo = new PDO(
'mysql:host=localhost;dbname=my_db;charset=utf8mb4',
'my_user',
'my_password',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION],
);
With MySQLi, select it through the driver API:
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$connection->set_charset('utf8mb4');
The old mysql_* extension is unavailable in PHP 8 and must not be used.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents