views:

128

answers:

4

I'm trying to save some values from a form in CakePHP into a MySQL database and when the values go into the database they are getting html encoded.

So something like (#45) gets stored in the database as (#45) and then when someone tries to go back and edit the form they see all the extra characters.

I've tried setting the encoding on the database connection to utf8 like this:

private $production = array(
    'driver' => 'mysql',
    'persistent' => true,
    'host' => 'localhost:3306',
    'login' => '',
    'password' => '',
    'database' => 'db',
    'prefix' => '',
    'encoding' => 'utf8'
);

and have this set in my configuration:

Configure::write('App.encoding', 'UTF-8');

and also added this to my default layout:

echo $html->charset();

Any Ideas?

+1  A: 

Since it is further down the line, that should be pretty easy to figure out where it is happening. A one stop lazy solution to debugging PHP:

print_r($data); die;

But you are probably already doing that.

sims
In Cake you can just use `pr($data);`
NullUserException
A: 

is the mysql itself in UTF-8 though? do a mysql export / dump and see what it says after each table!

boobyWomack
+1  A: 

Hi Nick,

I have confirmed, that all settings (database.php, core.php, default.ctp) you have done so far are identical to mine (except that you use persistent=true, but that should be no issue imho). Setting the database as well as every table manually to utf8_unicode_ci (via PHPmyAdmin) is the only thing I have done in addition to this.
I think the later step isn't even necessary, as tables are created according to the encoding of the db. Make sure that the db and tables are encoded correctly, then make sure that you actually use this setting, in case you have defined multiple database connections.

Kind regards, Benjamin.

benjamin
A: 

I found where the encoding was happening. In the AppModel class it was calling Sanitize::clean without 'encode' set to false

function beforeSave() {
    if (!empty($this->data)) {
        $this->data = Sanitize::clean($this->data, array('escape' => false, 'carriage' => true));
    }       
    return parent::beforeSave();
}

Once I set encode to false for the clean method it worked correctly

function beforeSave() {
    if (!empty($this->data)) {
        $this->data = Sanitize::clean($this->data, array('escape' => false, 'carriage' => true, 'encode' => false));
    }       
    return parent::beforeSave();
}
Nick