【问题标题】:CakePHP 3.0: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntaxCakePHP 3.0:SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误
【发布时间】:2015-08-21 07:55:20
【问题描述】:

我在 CakePHP 3.0 中使用 Form 将数据保存到数据库。

//add.ctp
<div>
    <?= $this->Form->create($deposit) ?>
    <fieldset>
        <legend><?= __('Add') ?></legend>
        <?php
            echo $this->Form->input('date');
            echo $this->Form->input('profile_id', ['options' => $profiles]);
            echo $this->Form->input('amnt');
            echo $this->Form->input('desc');
            echo $this->Form->input('user_id', ['options' => $users]);
        ?>
    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
</div>

这是我的添加功能

public function add()
{
    $deposit = $this->Deposits->newEntity();
    if ($this->request->is('post')) {
        $deposit = $this->Deposits->patchEntity($deposit, $this->request->data);
        if ($this->Deposits->save($deposit)) {
            $this->Flash->success(__('The member deposit has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The member deposit could not be saved. Please, try again.'));
        }
    }

    $profiles = $this->Deposits->Profiles->find('list', ['limit' => 200]);
    $users = $this->Deposits->Users->find('list', ['limit' => 200]);
    $this->set(compact('deposit', 'profiles', 'users'));
}

当我提交我在数据库语法错误下方找到的表单时

错误:SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 'desc, user_id, created, modified) 附近使用的正确语法 VALUES ('2015-06-06', 7, '3211', 'some text', 1,'在第 1 行

显示 SQL 查询:

INSERT INTO member_deposits (date, profile_id, amnt, desc, user_id, created, modified) VALUES (:c0, :c1, :c2, :c3, :c4, :c5, :c6)

我花了很多时间通过谷歌搜索和Similar Post 解决了这个问题,没有运气,但花了一天后我发现只需将 quoteIdentifiers 配置为 true 即可解决>.

quoteIdentifiers 在你的 cake 项目的 Datasources 下的 config/app.php 中默认设置为 false。

【问题讨论】:

  • 我不知道 cakePHP,但我怀疑这是您对列 'DESC' 的保留字的不幸使用 - dev.mysql.com/doc/refman/5.0/en/reserved-words.html。找到一种方法来转义字段名称(例如desc)或更改列名称。
  • 这里有问题吗?
  • @crafter,如果我将列 desc 更改为任何内容,它就会起作用。谢谢。
  • @ndm,我刚刚分享了我的经验。谢谢
  • 我明白了,这是值得称赞的,但在这种情况下,它是重复的:stackoverflow.com/questions/27854333/… 在旁注中,回答您自己的问题,因此非常欢迎分享经验,但建议您将解决方案作为实际答案发布,以便问题看起来已解决,另请参阅 stackoverflow.com/help/self-answer

标签: mysql cakephp-3.0


【解决方案1】:

您的一个列正在使用 MySQL 保留的列名。

dev.mysql.com/doc/refman/5.0/en/reserved-words.html

如您所见,DESC 是保留的。

如果您能找到一种方法来更改查询以使用转义列名指定,mysql 将容忍这种情况。例如

INSERT INTO `member_deposits` (
    `date`, `profile_id`, `amnt`,
    `desc`, `user_id`, `created`, `modified`) 
VALUES (:c0, :c1, :c2, :c3, :c4, :c5, :c6)

或者,将列名更改为不违反 mysql 保留字规则的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    相关资源
    最近更新 更多