0

I'm trying to execute an SQL INSERT but I am getting the error:

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) VALUES (example@example.com, hello)' at line 1

The values in the table are: id(auto increment), email and key which are both varchar(255) with the id being (int).

function validate($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

$key = 'hello';
$email = validate($_POST['email']);

$insert = $user->recordPasswordReset($email, $key);


public function recordPasswordReset($email, $key)
{
    try 
    {
        $db = DB();
        $sql = "INSERT INTO password_reset(email, key) VALUES (:email, :key)";
        $stmt = $db->prepare($sql);
        $stmt->bindParam(':email', $email, PDO::PARAM_STR);
        $stmt->bindParam(':key', $key, PDO::PARAM_STR);
        $stmt->execute();
    } 
    catch (PDOException $e) 
    {
        echo ($e->getMessage());
    }
}

Can anybody see any errors in my code?

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
TJDev
  • 133
  • 3
  • 13

1 Answers1

1

Firstly, as per the documentation, your field name key is a reserved keyword. You need to use back ticks around it.

Change,

INSERT INTO password_reset(email, key) VALUES (:email, :key)

To,

INSERT INTO password_reset(email, `key`) VALUES (:email, :key)

Secondly, please don't use an all-in-one sanitize function as they generally have some form of flaw in them.

Thirdly, you are using visibility keywords outside of a class.

Script47
  • 14,230
  • 4
  • 45
  • 66