PHP, MySQL and Japanese characters

PHP, MySQL and Japanese characters

November 16th, 2008 | written by

I recently set up a photoblog for my wife. As Junko is Japanese she wanted the ability to write posts in her mother tongue. WordPress handles this perfectly well out of the box but when I came to interrogating the WordPress database to display the latest blog titles on an external page I was just getting ????. The character encoding of the page was set to utf8 and the collation of the MySQL database and all it’s tables was also set to utf8_unicode_generals so I was baffled.

I disovered that the reason this was happening is because the default encoding of a php-MySQL connection is utf8. So the solution turns out to be very simple: set the econding for the query session to utf8 with the query: mysql_query(“SET NAMES ‘utf8′”, $connection);

1
2
3
4
5
6
7
8
9
mysql_select_db($database, $connection);
 
mysql_query("SET NAMES 'utf8'", $connection);
 
$query = "SELECT * FROM table ";
 
$result = mysql_query($query, $connection) or die(mysql_error());
 
$row = mysql_fetch_assoc($connection);

If you are using PHP 5.2 or later you need to use instead:

mysql_set_charset(‘utf8’,$connection);


Category : MySQL &php &Tutorials

Leave a message/Contact me

Latest Blog Entries

Testimonials

"We used Simon to help us get our new website up and running. He is expert at what he does, and I am happy to recommend him without reservation." [More...]

Mike Cranny, Director Create Solutions Ltd

Search


Blog feed Blog Feed

SJC Digital Photograpy SJC Digital Photography