Tuesday, December 8, 2009

how to insert uft8 data in a latin1 structure tables/DB

I have been so problematic these past few days with a mysql insertion problem.Every time when i tried to insert a text that contains "‘" left single quote, "’" right single quote, "“" left double quote and "”" right double quote or what they call it a prime or anything that is to be treated as a html special character when i look the data in the Database they will be transformed into a strange characters that contains euro "€", i don't know why.

When i'm going to retrieve those data, they will be display the same strange characters that are in DB.
I think there is a problem with the structure of our DB. The collation type of every table of our
Database is "latin1_swedish_ci".

They say that we need to transform the collation type of our DB to "utf8_general_ci" in order to
overcome this problem. But sad to say, its no used. It is still the same.
I have been searching and searching for answers in days, just to find out how to solve this problem.
At last, after a days of searching i found the solution.

If you are also experiencing something like this, here is the solution.

In your mysql insertion query like "INSERT INTO example (name, age) VALUES ('Timmy Mellowman', '23' )"
add "_utf8" before the inserted data to any text/varchar/char DB datatype that you want to fix.

It should look like this now "INSERT INTO example (name, age) VALUES (_utf8'Timmy Mellowman', '23' )".

"_utf8" => This function will convert text in utf8 format so that when you retrieve those saved
data, you will not be seeing anymore strange characters that contains euro "€".

But wait, when you retrieved the data from DB and if you will going to see "?" question marks instead of html special characters. You need to execute this query "set names utf8" before displaying the query results.


mysql_query("SET names utf8");
$result = mysql_query("select * from example");

Now, this will fix the problem.

No comments: