All posts in MySQL

DBAL and UTF-8 encoding problem

If you are using Doctrine DBAL to connect to your database you will notice that even if you are using UTF-8 encoding in your database tables the special characters are still not rendered correctly.

This is because by default the connection opened by DBAL is not UTF-8.

You will also notice that the documentation on setting connection charset (or other options) doesn’t exists for the DBAL package. Actually there is some but just to be something there.

So…

Create your connection:

1
2
3
4
$connectionParams = array(
..
);
$dbh = Doctrine\DBAL\DriverManager::getConnection($connectionParams, null);

And after you create the conexion add this:

1
2
3
$dbh->query('set names "utf8"');
$dbh->query('set character_set_server="utf8"');
$dbh->query('set collation_connection="utf8_general_ci"');

That’s it.

Popularity: 1% [?]