Matt Lowden

I work here, created this and released these.

Character Sets in PHP & MySQL

July 7th 2011 at 20:12PM

If you are using PHP and MySQL and experiencing problems displaying certain characters stored in a MySQL database then the following guide should help you out.

First ensure that you are telling the browser to render all text in UTF-8. Before you send any content to the browser write the following line.

header('Content-Type: text/html; charset=utf-8');

Make sure that you are also sending the same definition to the browser within the <head> tag.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Now, thats the easy part. The most common cause of character set problems, in this instance, is inconsistencies between how the data is provided by MySQL and how it is displayed by PHP.  As soon as you connect to your database, execure the following query (Where $db_con is the database connection resource). This ensures that data to and from the database is handled in the UFT-8 character set.

mysql_query("SET NAMES utf8", $db_con);

For the most-part this will be sufficient but when dealing with certain European and Asian characters you'll also want to change the database and field character sets. For your database execute the following query in MySQL.

ALTER DATABASE `database_name` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci

For each table execute the following.

ALTER TABLE `table_name` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci

For each field execure the following - obviously remember to replace 'CHAR(15) with your field's type definition.

ALTER TABLE `table_name` CHANGE `field_name` `field_name` CHAR( 15 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL