jump to navigation

Mysql and UTF-8 February 11, 2006

Posted by rossoft in CakePHP.

After updating my mysql database to utf8, I had several problems with the encoding. Finally I discovered the solution: You must specify the encoding after the connection to the database through sql. Somewhere in your code you have to put the instruction:
mysql_query(“SET NAMES ‘utf8′”);

I have done a simple component for it (this is not a controller issue, but model issue, but a before filter in my AppModel dislikes me… and doesn’t exist any type of components in the model so…)

class MysqlComponent extends Object
	function startup(&$controller)
		//Changes the encoding of mysql to UTF-8
	 	mysql_query("SET NAMES 'utf8'");		


1. saavedrajj - April 23, 2006

hi, could you explain how I can use your code? I mean
in order the run it with my CakePHP app.


2. rossoft - April 24, 2006

in your AppController
var $components=array(…..,'mysql');

3. Tobi - May 23, 2006

an imho more elegant/less overheaded solution is to overwrite the model constructor like this:
function __construct()
static $changedSet=false;
$this->query(“SET NAMES ‘utf8′”);

4. anarchitect - August 4, 2006

Hi Miguel,

I have used your component approach, but when i like to add elements to views, i get funny questionmarks instead of the special chars.

I have started thread in the google group:

Do you have any clues/advice? Thanks.

5. Blackwolf - March 9, 2007

If you want to make your application really UTF8-ready, you actually need three queries instead of one:

SET NAMES ‘utf8’;
SET SESSION collation_connection = ‘utf8_general_ci’;

And among the HTTP headers, send:

Content-type: text/html; charset=utf-8

6. Sorin - August 29, 2007

Cake 1.2 now supports this natively. Just add ‘encoding’ => ‘UTF-8’ to
your database configuration and the querying is taken care of
automatically at the database level.

… found here: http://groups.google.com/group/cake-php/browse_thread/thread/902d931ff87eb8ac/c4ca2c14891df179

7. Christoph - September 12, 2007

Make sure to use ‘encoding’ => ‘utf8′!! ‘UTF-8’ won’t work!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: