Nov 09 2009

Stop UTF8 problems with special characters

Category: MySql,PhpGiulio Pons @ 4:04 pm

I’m italian and I always need to use special chars like è é à ù. The same need belongs to french developers, and many other non-english developers. To use special chars without encoding problems try to follow this 4 rules:

  1. create fields on db with utf8_general_ci collation
  2. make the query ‘set names’ after any connection (look the block code below, you need mysql 5)
  3. put meta charset utf8 tag in the html head block
  4. read and write strings to db and to html without using utf8_encode or other functions
  //after connecting to your db make this query:
  mysql_query("SET NAMES 'utf8';");

NOTE (added on 2010-02-16)
Sometimes these steps do not work, and you start say f**ck f**ck! Well, it’s also happened to me, and I’ve notice that sometimes php.ini make some problems because it has a wrong default charset setted. So, if this is your problem, put this line at the beginning of your php files:

ini_set('default_charset', 'UTF-8');
Share

Related posts:

  1. 10 PHP usefull functions for MySQLi stuff (mysql improved)
  2. PHP function to fix collation on database fields of MySQL

Tags: , , ,

One Response to “Stop UTF8 problems with special characters”

  1. ghazal says:

    Hi,
    I can’t thank you enough for this little trick. I have been stuck for months (yes, months !) with an accented characters pb (in french) involving a datagrid/PHP/a JS framework and json encode and this neat trick solved it in a breeze. You made my day today.
    THANK YOU !!!!!

Leave a Reply