Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Setting utf-8 encoding while selection data from Mysql db

I have some french data with these caracters : àéçè... etc When I store data and encode it to Json, values with these special chars are set to null so I did utf8_encode($myString) for each value of my array to encode to json after.

This is boring, is there a way to encode data in the mySql way with the ORM of Phalcon?

edited Mar '14

Yes, of course. You can set utf-8 as default in php.ini

default_charset = "UTF-8"

And additionally set your mySQL

default_character_set = utf8

init_connect=‘SET collation_connection = utf8_unicode_ci’

edited Mar '14

Just add encoding to your application`s db adapter like below:

        // Database
        $di->set('db', function() use ($config) {
            return new Phalcon\Db\Adapter\Pdo\Mysql(array(
                'host'     => 'localhost', // $config->db->host
                'username' => 'root',
                'password' => '1234',
                'dbname'   => 'test',
                'charset'  => 'utf8' // ITS THE BEST SOLUTION

and add following meta to your main layout

    <meta charset="utf-8">

These are enough for working with any utf-8 encoding application. and make your database with following charset and collation too


Isn't this a little bit risky if your database is set to something different than utf-8? You're then going to save utf-8 encoded strings in your database which probably isn't utf-8 but something else like latin1 for example. This will result in mixed character encoded data in your database.

I would first change the database so that your database server is running in utf-8 and all your databases are in utf-8 before changing anything on the php side.


@Gregor Panek Yes my MySql db is running in utf8_general_ci which I think is the best ?

@a6oozar: thx man this is what I wanted :)

@sn0opr ok than there should be no problem :)