Fixing UTF-8 encoding problems on MySQL queries with PHP

Posted by Danny Herran on Aug 24, 2010 in Backend | 4 comments

It happened to me a lot of times, I had my connection set to UTF-8, my database was UTF-8, even my tables and every single field, however, for some reason, the information I updated in phpMyAdmin wasn’t being displayed correctly on my website and the information edited on my website wasn’t being displayed correctly in phpMyAdmin.

You know all those weird characters, those that very often come up when you write accented letters or words in another language like Portuguese or Spanish? That’s what I am talking about.

Here is the solution. A single line that can save you hours of research.

Reading quite a bit, I came across a very valuable information inside the MySQL documentation which definitely solved my problem.

mysql_query("SET NAMES 'utf8'");

So, if all your databases/tables has been built under UTF-8 and you still have inconsistencies in the data being displayed, add that line to you code, as the first query you run after you do your mysql_connect().

For example:

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_selected = mysql_select_db('foo', $link);
mysql_query("SET NAMES 'utf8'");

That’s it. After that, you can run all your queries, and the fetched data will look perfectly. If you are working with your own MySQL class, make sure you run the SET NAMES right after you connect to the database.

Also, don’t forget to set your meta charset to UTF-8:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

More information on: http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html