Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

Setting UTF-8 for Propel with MySQL tables

Since it can be annoying to have Propel ignore collation of tables in MySQL >= 4.1, you must force Propel to use UTF-8 collation by running the SET NAMES UTF8 SQL query.

In order to do that, you specify a filter that executes at every request. Specify the following code in filters.yml:

myUtf8ConnectionFilter:
  class: myUtf8ConnectionFilter
  activate: on

Create a new file called myUtf8ConnectionFilter.class.php in your application's lib folder and insert the following code:

<?php
class myUtf8ConnectionFilter extends sfFilter
{
  public function execute($filterChain)
  {
    $con = Propel::getConnection();
    if ($con){
       $con->executeQuery("set names utf8");
    } else {
      throw new Exception($e);
    }
    $filterChain->execute();
  }
}
?>

The code was copied from this website - I am not asserting any authorship.

by Klemen Slavič on 2006-06-19, tagged collation  propel  utf8 

Comments on this snippet

gravatar icon
#1 brikou on 2006-08-14 at 12:59

Or you can just add this to the mysql configuration file (my.ini or my.cnf): init-connect="SET NAMES utf8" (but beware not to use root user...)

gravatar icon
#2 romus on 2006-08-24 at 09:43

If you use more than one database and modification of mysql config file could be problem, You may take a look at code below - it's a modified version of above snippet:

class myUtf8ConnectionFilter extends sfFilter {

  public function execute($filterChain)
  {
        $databases_conf = Propel::getConfiguration();
 
        if( is_array($databases_conf[&#039;datasources&#039;]) )
        {
            foreach(array_keys($databases_conf[&#039;datasources&#039;]) as $db_name)
            {
                // domyslna baza &#039;default&#039; wskazuje na jedna z rzeczywistych baz
                if( $db_name==&#039;default&#039; )
                {
                    continue;
                }
                $con = Propel::getConnection($db_name);
                if($con)
                {
                      $con-&gt;executeQuery(&quot;SET names utf8&quot;);
                      //$con-&gt;executeQuery(&quot;SET character set utf8&quot;);
                }
                else
                {
                      throw new Exception($e);
                }
            }
        }
 
        $filterChain-&gt;execute();
  }

}

gravatar icon
#3 Fabien Potencier on 2006-09-21 at 09:48

In symfony > 0.9.2136, you can add an encoding parameter in your databases.yml configuration file.

gravatar icon
#4 sam.kuper on 2008-03-28 at 08:03

I'm running symfony 1.0.12 but the encoding parameter in databases.yml isn't working for me. I've set it to utf8 but my tables still end up with a collation of latin1_swedish_ci .

I'd be grateful for any advice you can offer.

You need to create an account or log in to post a comment or rate this snippet.