Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTF-8 problems PHP/MySQL

Tags:

php

mysql

utf-8

I've always used ISO-8859-1 encoding, but I'm now going over to UTF-8.

Unfortunately I can't get it to work.

My MySQL DB is UTF-8, my PHP document is encoded in UTF-8, I set a UTF-8 charset, but it still doesn't work.

(it is special characters like æ/ø/å that doesn't work)

Hope you guys can help!

like image 473
Mikkel Avatar asked Jan 07 '11 08:01

Mikkel


People also ask

Does MySQL support UTF-8?

MySQL supports multiple Unicode character sets: utf8mb4 : A UTF-8 encoding of the Unicode character set using one to four bytes per character. utf8mb3 : A UTF-8 encoding of the Unicode character set using one to three bytes per character.

How do I set MySQL database to UTF-8?

To change the character set encoding to UTF-8 for the database itself, type the following command at the mysql> prompt. Replace dbname with the database name: Copy ALTER DATABASE dbname CHARACTER SET utf8 COLLATE utf8_general_ci; To exit the mysql program, type \q at the mysql> prompt.

Is UTF-8 encoded PHP?

The utf8_encode() function is an inbuilt function in PHP which is used to encode an ISO-8859-1 string to UTF-8. Unicode has been developed to describe all possible characters of all languages and includes a lot of symbols with one unique number for each symbol/character.


2 Answers

Make sure the connection to your database is also using this character set:

$conn = mysql_connect($server, $username, $password);
mysql_set_charset("UTF8", $conn);

According to the documentation of mysql_set_charset at php.net:

Note:
This is the preferred way to change the charset. Using mysql_query() to execute 
SET NAMES .. is not recommended.

See also: http://nl3.php.net/manual/en/function.mysql-set-charset.php

Check the character set of your current connection with:

echo mysql_client_encoding($conn);

See also: http://nl3.php.net/manual/en/function.mysql-client-encoding.php

If you have done these things and add weird characters to your table, you will see it is displayed correct.

like image 192
Rene Terstegen Avatar answered Nov 15 '22 23:11

Rene Terstegen


Remember to set connection encoding to utf8 as well.

In ext\mysqli do $mysqli->set_charset("utf8")

In ext\mysql do mysql_set_charset("utf8")

With other db extensions you might have to run query like SET NAMES 'utf8'

Some more details about connection encoding in MySQL

As others point out, making sure your source code is utf-8 encoded also helps. Pay special attention to not having BOM (Byte Order Mark) - it would be sent to browser before any code is executed, so using headers or sessions would become impossible.

like image 9
Mchl Avatar answered Nov 15 '22 21:11

Mchl