Character encoding in MySQL

Posted: February 27th, 2010 | Author: | Filed under: MySQL | Comments Off on Character encoding in MySQL

Just a quick note on character encoding in MySQL, use the following to force MySQL into using UTF-8 for ever!

PHP

In your PHP, always use the following immediately after you set up your connection.

  • mysql_set_charset(‘utf8’, $oDB);
  • mysql_query(‘SET NAMES \’utf8\”);

The tricky bit lies in your MySQL configuration file:

my.cnf

Add the following lines:

[client]
default-character-set=utf8
[mysqld]
default-character-set=utf8
default-collation = utf8_general_ci

This tells MySQL that the client (which is either PHP or the system) expects UTF-8. If you don’t tell MySQL this, a mysqldump will produce ANSI and an import from the command line will result in double encodings.

And don’t forget to use utf8_general_ci for all databases, tables and fields!