We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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?



8.1k
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

[client]
default_character_set = utf8

[mysqld]
init_connect=‘SET collation_connection = utf8_unicode_ci’


10.5k
Accepted
answer
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

<head>
    <meta charset="utf-8">
    [...]
</head>

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

CREATE DATABASE `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

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.



22.8k

@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 :)