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