0

I have problem with PDO and can't find the solution:

My function:

public static function create($position, $name, $mail, $mailtext, $confirmed, $key, $formid) {
    global $database;

    try {
        $pdo_result = $database->prepare('INSERT INTO Form (Position, Name, Mail, MailText, Confirmed, Key, Form_idForm) VALUES(:Position, :Name, :Mail, :MailText, :Confirmed, :Key, :Form_idForm)');
        $pdo_result->execute(array(
            ':Position' => $position,
            ':Name' => $name,
            ':Mail' => $mail,
            ':MailText' => $mailtext,
            ':Confirmed' => $confirmed,
            ':Key' => $key,
            ':Form_idForm' => $formid
        ));

        return $database->lastInsertId();
    } catch(PDOException $e) {
        Page::error('Error: Message:', $e->getMessage());
    }

    return null;
}

Exception: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Key, Form_idForm) VALUES('Position', 'Name', 'Mail', 'MailText', '1', 'keeey', '' at line 1

4 Answers4

5

You're using reserved words in your field names.

Try escaping your INSERT-statement within your $database->prepare-construct like this:

INSERT INTO Form (
    `Position`, `Name`, `Mail`, `MailText`, 
    `Confirmed`, `Key`, `Form_idForm`)  .... 
Bjoern
  • 15,934
  • 4
  • 43
  • 48
3

Eventually because of the use of Key, a preserved MySQL word. Use another word instead or use backtick `.

by: https://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

ultima_rat0
  • 290
  • 2
  • 8
2

You can still use key if you want to. Just wrap it with backtick,

INSERT INTO Form (
    `Position`, `Name`, `Mail`, `MailText`, 
    `Confirmed`, `Key`, `Form_idForm`)

but as an advise, refrain from using any reserved keyword to avoid future problems. :)

MySQL Reserved Keywords List

underscore
  • 6,495
  • 6
  • 39
  • 78
1

key is a keyword in SQL. You can therefore not use it as a column name.

You should rename it, else it will cause issues like the one you are currently experiencing.. however you can "escape" the field names like so which will also rectify this issue:

INSERT INTO Form (`Position`, `Name`, `Mail`, `MailText`, `Confirmed`, `Key`, `Form_idForm`) VALUES(:Position, :Name, :Mail, :MailText, :Confirmed, :Key, :Form_idForm)');

You can find a full list of reserved words here: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html

likeitlikeit
  • 5,563
  • 5
  • 42
  • 56
Jake Ball
  • 798
  • 2
  • 8
  • 26