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.
-
class AppModel extends Model{
-
function __construct($id = false, $table = null, $ds = null) {
-
$db =& ConnectionManager::getDataSource($this->useDbConfig);
-
$db->execute('SET NAMES utf8');
-
}
-
$utf8Enabled[$this->useDbConfig] = true;
-
}
-
parent::__construct($id, $table, $ds);
-
}
-
}
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
7 Comments
Mariano: Wooooooo! How cool is that, thanks : p.
Ah, because you mentioned the dessert series I couldn't focus on your blogpost itself, it made me think of the great face-in-cake picture :')
Felix Geisendorfer's Blog: Enforce utf8 for multiple db connections...
Felix Geisendorfer has another quick CakePHP tip - an update from ......
[...] Felix Geisendorfer has another quick CakePHP tip - an update from a previous tip for forcing utf8 connections on multiple databases: 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. [...]
ConnectionManager::getDataSource($this->useDbConfig);
sorry, but your blog cut my text because I use < ... no comment


Or if you are using CakePHP 1.2 just set the 'encoding' setting on your configuration per connection, such as:
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'password',
'database' => 'database',
'schema' => '',
'prefix' => '',
'encoding' => 'utf8'
);