Search code examples
phpdatabasepdoprepare

PHP PDO: Syntax error or access violation (Help)


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


Solution

  • 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`)  ....