Kristoffer la Cour
Kristoffer la Cour

Reputation: 2576

Double UTF-8 encoding, but why? PHP/MySQL

I have some forms, that insert some data into a MySQL database, and for some reason the characters get double utf-8 encoded. You don't see it on the front-end of my website, but in the back-end you do, if i look at the data from phpmyadmin, it's double encoded.

Also, to display data entered from phpmyadmin i have to utf8_encode it.

If i use uft8_decode() on my data before i put it into my database, it works, but then i'd have to use utf8_encode() again to display my data properly, and i would like to find a better solution that re-writing most of my code.

The characters i'm dealing with is the danish æ, ø and å characters.

I have every setting i can find in php.ini set to utf-8, every thing i can find in phpmyadmin to utf8, html meta tag set to utf-8, and still i have this error to deal with.

So my question is, does anyone know why this happens, or how i could fix it?..

Update: After running the mysql code Jako suggested, the data is properly encoded in the back-end of the database when it comes from the front-end, but i still need to run utf8_encode() to display the data properly on the front-end, any ideas?..

Update 2: Again, after running the code from the answer to this question i still had problems, the encoding was now on and off utf8, and i suspect phpmyadmin for resetting the encoding somehow. I found a new way of doing things, and it works flawlessly, described in my answer below...

Upvotes: 3

Views: 3165

Answers (2)

Kristoffer la Cour
Kristoffer la Cour

Reputation: 2576

Okay, i found the answer!! I searched a bit more, (have been doing so for hours) and found this question: Whether to use “SET NAMES”

Using the answer from that question i ran this query:

mysql_query("SET character_set_client = UTF8");
mysql_query("SET character_set_results = UTF8");
mysql_query("SET character_set_connection = UTF8");
mysql_query("SET names UTF8");

That's it, it works fine now on all my php scripts. Still thanks to Jako for leading me in the right way. ;)

Update: Okay, since the encoding was on and off and the settings didn't stay that way i found a new solution that works. I added mysql_set_charset() to my connection script:

mysql_set_charset("UTF8");

It gives me the right data from the database every time and inserts the right data as well, so this was only one line of code.

Upvotes: 2

Jako
Jako

Reputation: 4901

I ran into similar issues in the past and this did the trick for me.

mysql_query("SET names UTF8");

Upvotes: 5

Related Questions