使用 ZF2 dbAdapter 进行 mySQL 更新时 UTF-8 错误编码

UTF-8 Bad Encoding when Using ZF2 dbAdapter for mySQL for Update

当我尝试使用 "tableGateway" 对象更新记录时出现异常:

Zend\Db\Adapter\Exception\InvalidQueryException
Statement could not be executed 
(HY000 - 1300 - Invalid utf8 character string: 'C`\xC3`\xB3`digo')

我有以下 table 结构,数据在 mySQL 中:

CREATE TABLE `clientes` (
    `Código` int,
    `Nome` varchar(50),
    `Descricao` varchar(150)
   ....
);

INSERT INTO `clientes` (`Código`, `Nome`, `Descricao`)
VALUES (1, 'Test Nome', 'Test Descricao');

数据库编码为'latin1',但数据库配置如图:

'mycnn'    => array(
              'driver'         => 'pdo',
              'dsn'            => 'mysql:dbname={$mydb};host={$myhost}',
              'username'       => '{$myuser}',
              'password'       => '{$mypassword}',
              'driver_options' => array(
                    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
                ),
            )

如您所见,我已经为 "UTF-8" 设置了驱动程序,列名 "Código" 有一个特殊字符,无法重命名此列。

我在模型中用于更新的语法是:

$set = array("Nome" => "Edited Test");
$where = array("Código" => 1);

$this->tableGateway->update($set, $where);

之后,ZF 正在解析 SQL 抛出异常:

UPDATE "clientes" SET "Nome" = 'Edited Test' WHERE "C`\xC3`\xB3`digo" = 1

我也删除了 UTF-8 选项,因为目录是 "latin1_swedish_ci" 但没有成功。

如果有人能给我提示如何面对这个问题,我将不胜感激。

提前致谢。

确保你的数据库编码类型是UTF-8

'driver_options' => array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),

确保字段有 utf8_general_ci

在你的布局 phtml head 中有

<meta charset='utf-8'>

已更新

如您所说,您无法将编码更改为 utf-8,因此请使用以下命令之一使用 driver_options

'SET NAMES \'latin1\'' or 'SET CHARACTER SET \'latin1\''

有关详细信息,请查看 doc

当包含 latin1 字符的列名出现问题时

只需将条件作为字符串而不是数组作为第二个参数传递给 TableGatewayupdate() 方法。但是你必须在你的 driver_options.

中设置这个 'SET NAMES \'UTF8\''
$id = 1;
$where = "Código = {$id}";

// Or use this way
$where = "Código = 1";

$this->tableGateway->update($set, $where);