Error in PDO database

Asked

Viewed 115 times

3

I am creating a page that saves values in the Mysql database using PDO and is not writing the data. I am using the following code:

<?php
  $conexao = new PDO('mysql:host=localhost;dbname=dbTeste', 'root', '');

  $query = "INSERT INTO names(nome, email) VALUES('Wade', '[email protected]')";

  $stmt = $conexao->prepare($query);
  $stmt->execute();
?>

But it does not save the data in the database.

  • places a space after names (...) and another after VALUES (...)

1 answer

4


The problem is the name of your table NAMES is a reserved word from mysql, in which case it is mandatory to escape the name with crase ````

Change:

$query = "INSERT INTO names(nome, email) VALUES('Wade', '[email protected]')";

To:

$query = "INSERT INTO `names`(nome, email) VALUES('Wade','[email protected]')";
                      ^-----^

List of reserved words

  • 1

    That name Names I put as an example, actually users, except this, the rest is the same. And I tested with another table name too, and gives the same problem.

  • When vc copies and executes the direct query in the database which error returns?

  • When I run direct in phpMyAdmin it creates the line normally, but when I try the PHP page it does not create. I made a page to show the existing lines and does normally, but to insert, does not.

  • Is the bank autocommit enabled? @rogue_psycho

  • I don’t know what that means, I’ll take a look.

  • @rogue_psycho, after the execute(), add this line and see if it records, $conexao->commit();

  • Okay, I did, when I put this command started working. Thank you!

  • @rogue_psycho, autocommit is off so about commit/rollback and transactions see these questions: What is a Mysql Transaction for? and Mysql Transaction When? How? Why?

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.