Nestor
Nestor

Reputation: 559

Error inserting data into a table using doctrine and mssql

I'm trying to insert data into a created database with the corresponding table this way (Symfony4):

    /**
     * @Route("/admin/user/new", name="admin_add_new_user")
     */
    public function new_user(EntityManagerInterface $em)
    {
        $user = new User();
        $user->setUsername('felipito')
            ->setPassword('canelo123')
            ->setEmail('[email protected]');

        $em->persist($user);
        $em->flush();

        return $this->render('admin/index.html.twig', [
            'controller_name' => 'AdminController',
            'brand' => 'brand',
            'msg' => sprintf(
                'New user dude: id #%d user %s', $user->getId(), $user->getUsername()
            )
        ]);
    }

Once I open the url it throws the following:

An exception occurred while executing 'INSERT INTO user (username, roles, password, email) VALUES (?, ?, ?, ?)' with params ["felipito", "[]", "canelo123", "[email protected]"]:

SQLSTATE [42000, 156]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near the keyword 'user'.
SQLSTATE [42000, 8180]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared.

Maybe the problem is related with this problem I had yesterday

Upvotes: 1

Views: 441

Answers (2)

Nestor
Nestor

Reputation: 559

Like @rodmar-zavala answered, the problem is I was using a reserved word in sql server. It also applies to this error I got when making the migration on doctrine.

So I refactored the class name and it worked OK.

Upvotes: 1

Rodmar Zavala
Rodmar Zavala

Reputation: 137

looks like user is a reserved word in MySQL. Update your User entity @ORM\Table annotation like this.

 use Doctrine\ORM\Mapping as ORM;

 /**
 * @ORM\Entity
 * @ORM\Table(name="`user`")
 */
class User extends BaseUser
{
  // [....]
}

Note the name of the table is using single quotes.

Upvotes: 1

Related Questions