0

Possible Duplicate:
SET NAMES utf8 in MySQL?

I am writing PHP to connect to a MySQL database. I have seen some examples that sets the encoding to UTF8 mysql_query("SET NAMES utf8");

Why is this done? What are the advantages to doing this and what problems does it avoid?

Community
  • 1
  • 1
Colin747
  • 4,955
  • 18
  • 70
  • 118

3 Answers3

2

This way the database will return data in UTF8 encoding (and expect such if you are inserting/updating). Useful if you are trying to query non-ascii characters from the server and displaying the content in general in UTF8 format, with UTF8 encoding headers. Otherwise you will see broken characters.

Especially useful if the data in the database is in non-ascii and non-utf8 encoding/collation (like CP-1251 for cyrillic) or if you have multiple collations in same database. This way you ensure that you are getting/putting all the data in single universal encoding, that you both understand and like :)

In general, it's a good practice. Most of the time you can't ensure you don't have data in non-ascii characters or there won't be such to insert. So it's just good practice to do it always, as UTF8 seems to be the widely accepted and loved data encoding these days.

ddinchev
  • 33,683
  • 28
  • 88
  • 133
0

The MySQL reference answers this pretty succinctly: http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html Be sure to try using google before SO :/ While I don't mind so much, many people really do.

dudewad
  • 476
  • 4
  • 8
0

By doing this you are telling php to communicate with mysql in UTF-8. The cost of running this line of code is near zero. There won't be any disadvantages regarding performance. If you do not wish to use this and have the permission, you should change it from your mysql settings.

Please refer to the following link: http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html

Ahmet Özışık
  • 443
  • 3
  • 11