Archive for March, 2010

When your PHP-MYSQL implementation has to deal with special characters (umlauts), you might wanna pay close attention to your setup. Usually, it doesn’t work right out of the box and if only one tiny piece of your puzzle is missing, chances are high your characters won’t get displayed as desired.

Let’s assume we have some data in our MYSQL database we simply wanna get via PHP. Standard procedure would be something like this:

Connect to database:

<?
$conn = mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db('databaseName', $conn) or die(mysql_error());
?>

Get data and print them on screen:

$sql = mysql_fetch_array(mysql_query("SELECT * FROM myTable"), MYSQL_ASSOC);
echo $sql['fieldInTable'];

In case you are using characters in english language only, the above will work as expected.

But what if your data contain umlauts, like “Ö”, “Ü”, “ß”, etc…? Well, you might see some weird letters instead and that’s what probably brought you here, right? :)

If you do some quick internet research on this topic, you will find countless discussions and possible solitions. However, if none of them worked for you so far, try the following:

Connect to database:

<?
$conn = mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db('databaseName', $conn) or die(mysql_error());
mysql_query("SET NAMES 'utf8'"); //this is new
mysql_query("SET CHARACTER SET 'utf8'"); //this is new
?>

Get data and print them on screen:

$sql = mysql_fetch_array(mysql_query("SELECT * FROM myTable"), MYSQL_ASSOC);
echo utf8_decode($sql['fieldInTable']); //this is new

In case it still doesn’t work, make sure your PHP document is UTF-8 encoded. Depending on the code editor you are using, you should easily be able to change encoding.
For example, in CODA it works like this:

It took me quite some time to figure this out, so hopefully you might find it helpful.

An App, you might like:
We recommend…
You might also like…
Get Adobe Flash playerPlugin by wpburn.com wordpress themes