Enforce utf8 for multiple db connections

Posted by Felix Geisendörfer, on Nov 10, 2007 - in PHP & CakePHP » DataSources, Models & Behaviors

Deprecated post

The authors of this post have marked it as deprecated. This means the information displayed is most likely outdated, inaccurate, boring or a combination of all three.

Policy: We never delete deprecated posts, but they are not listed in our categories or show up in the search anymore.

Comments: You can continue to leave comments on this post, but please consult Google or our search first if you want to get an answer ; ).

Hey folks,

this is just a quick update for Dessert #6 - MySql & UTF-8. I've been using the approach outlined in that old post pretty much until today, when I realized that it has two major flaws: It does not work when using multiple db connections (i.e. using load balancing or connecting to a 3rd party db), and it might interfere with other databases that don't need this utf8 thing to be set.

In order to fix it I came up with this improved version of the code.

php
  1. class AppModel extends Model{
  2.    function __construct($id = false, $table = null, $ds = null) {
  3.       static $utf8Enabled = array();
  4.       if (!isset($utf8Enabled[$this->useDbConfig])) {
  5.          $db =& ConnectionManager::getDataSource($this->useDbConfig);
  6.          if (low(get_class($db)) == 'dbomysql') {
  7.             $db->execute('SET NAMES utf8');
  8.          }
  9.          $utf8Enabled[$this->useDbConfig] = true;
  10.       }
  11.       parent::__construct($id, $table, $ds);
  12.    }
  13. }

This will make sure the 'SET NAMES utf8' query is only run for MySql connections and if there are more then 1 used, then each gets the query executed exactly once.

HTH,
-- Felix Geisendörfer aka the_undefined