Process A String With A Function Before Sending It To Db

I have an admin-section in my webapp where you can write blogposts, however, I want to be able to encode the text im writing with a php-function before saving it into the database.

I can’t controle the database because it’s not mine, and it has trouble with the encoding. So everything that goes in and out of the database needs to be encoded with the function below.

mb_convert_encoding($model->content, "utf-8", "IBM-850")

Where do I put this function if I need it to convert the data before saving it into the database?

I’v tried in the models rules()-function but no luck.

In a perfect world this is a database’s job.

See your DB (MSSQL?) documentation for details.

Also take a look at this:

and this: (this is how MySQL works)

PS. In case of some weird databases that don’t support client encoding you can use beforeSave and afterFind callbacks in your models.

Thanks for the fast reply.

yeah, im using MSSQL 2000, feels like I have tried everything to get the encoding correct. Even had help from a friend who have a lot of experience with MSSQL.

So I gave up and now im using that function everywhere :confused:

Do you know how I can use this part of the “set up unicode” guide? (I don’t know where to put the code)

SET NAMES utf8 ;

Such a command can be put in the initSQLs attribute of the db component. The charset attribute introduced above should be sufficient, though.

You should put this code in the main.php (the main configuration file under the database setup portion)

According to CDbConnection::initConnection you can use ‘initSQLs’ param in the main config file.



    'connectionString' => 'mssql:host=...;dbname=...',

    'username' => '...',

    'password' => '...',

    'initSQLs' => array(

        "SET ...",



PS Here’s how the initConnection looks like:



 * Initializes the open db connection.

 * This method is invoked right after the db connection is established.

 * The default implementation is to set the charset for MySQL and PostgreSQL database connections.

 * @param PDO $pdo the PDO instance


protected function initConnection($pdo)



    if($this->emulatePrepare!==null && constant('PDO::ATTR_EMULATE_PREPARES'))






            $pdo->exec('SET NAMES '.$pdo->quote($this->charset));




        foreach($this->initSQLs as $sql)




As you can see, SET NAMES is executed only for Postgres and Mysql.

I am sure you can set the encoding for your database server in case you want to know how you can perform that function before all your save calls you can use Active record hooks

Thanks! Will give it a shot!