Zend_Db_Table UTF-8 Characters

zend-dbzend-db-tablezend-framework

Tables in my database are created with a correct UTF-8 charset like this:

CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT,
...
...
...
...
...
PRIMARY KEY (id)
) ENGINE = INNODB  CHARACTER SET utf8 COLLATE utf8_slovak_ci;

However, when I use Zend_Db_Table to fetch the data from the table with this method:

public function getSingle($id)
{
    $select = $this->select();
    $where = $this->getAdapter()->quoteInto('id = ?', $id, 'INTEGER');
    $select->where($where);
    return $this->fetchRow($select);
}

It returns an object with messed up UTF-8 characters (converted to iso-8859-1 I guess).

When I look in the database through phpmyadmin, it shows up all characters correctly and it also shows correct encoding (UTF-8) so I don't know where's the problem.

How can I solve this problem?

UPDATE:

So I did this and it works:

protected function _initDb()
{
    $this->configuration = new Zend_Config_Ini(APPLICATION_PATH
                                               . '/configs/application.ini',
                                               APPLICATION_ENVIRONMENT);
    $this->dbAdapter = Zend_Db::factory($this->configuration->database);
    Zend_Db_Table_Abstract::setDefaultAdapter($this->dbAdapter);
    $stmt = new Zend_Db_Statement_Pdo($this->dbAdapter,
                                      "SET NAMES 'utf8'");
    $stmt->execute();
}

Is there some better way?

UPDATE2:

I tried this:

protected function _initDb()
{
    $this->configuration = new Zend_Config_Ini(APPLICATION_PATH
                                               . '/configs/application.ini',
                                               APPLICATION_ENVIRONMENT);
    $this->dbAdapter = Zend_Db::factory($this->configuration->database);
    $this->dbAdapter = Zend_Db::factory($this->configuration->database->adapter,
                                        $this->configuration->database->params->toArray()
                                        + array('driver_options' => array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")));
    Zend_Db_Table_Abstract::setDefaultAdapter($this->dbAdapter);
}

And I get an error:

Fatal error: Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' in C:\wamp\www\bakalarka\application\Bootstrap.php on line 46

Best Answer

Instead of setting driver_options, you can easily do the following.

Your ini file:

db.adapter         = Pdo_Mysql
db.params.host     = localhost
db.params.dbname   = mydb
db.params.username = myuser
db.params.password = mypass
db.params.charset  = UTF8

Note last parameter. Then read your config using Zend_Config_Ini:

$config = new Zend_Config_Ini('application.ini');

And pass database parameters as config subobject:

$db = Zend_Db::factory($config->db);
Related Topic