无法使用Symfony 4中的Doctrine2 DBAL \ Connection插入数据

时间:2018-11-05 23:00:22

标签: php symfony doctrine-orm doctrine symfony4

我正在尝试使用Doctrine2 DBAL \ Connection在MySQL表中插入一些数据(对于我不想映射的表),使用以下代码:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\DBAL\Connection;

class UtilsController extends AbstractController
{
    /**
     * @Route("/utils/fixer", name="utils_fixer")
     */
    public function dataFixer(Connection $conn)
    {
        $sql = "INSERT INTO test(id, username) VALUES (':id', ':name')";

        $id = 456;
        $name = 'blabla';

        $res = $conn->executeUpdate($sql, ['id' => $id, 'name' => $name]);

        return $this->render('utils/index.html.twig', ['res' => $res]);
    }
}

这是我的桌子的样子:

enter image description here

这是给我的:“ SQLSTATE [HY000]:一般错误:1366错误的整数值:第1行的列'id'的':id'”。

“ ID”字段没有自动递增,它只是一个测试表。

SELECT语句返回数据正常。

值绑定似乎不起作用??

我使用了该学说documentation

2 个答案:

答案 0 :(得分:1)

不应该使用占位符。

至少这给出了 executeUpdate()方法的用法示例。

public function dataFixer(Connection $conn)
{
    $sql = "INSERT INTO test(id, username) VALUES (:id, :name)";

    $id = 456;
    $name = 'blabla';

    $res = $conn->executeUpdate($sql, ['id' => $id, 'name' => $name]);

    return $this->render('utils/index.html.twig', ['res' => $res]);
}

答案 1 :(得分:0)

如果该值是自动递增的,则不应插入$ id的值-正如我认为的那样。