Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO MySQL prepared INSERT syntax error

Have seen tons of similar questions but still can't find out what's going on.

I'm using PHP's PDO to prepare a statement like that:

try{
    $statement = $db->prepare("INSERT INTO $date (name, surname, email, phone, comment) VALUES (:name, :surname, :email, :phone, :comment)");
    $statement->bindParam(':name', $name);
    $statement->bindParam(':surname', $surname);
    $statement->bindParam(':email', $email);
    $statement->bindParam(':phone', $phone);
    $statement->bindParam(':comment', $comment);

    $statement->execute();
}
catch(PDOException $e){
    die("Connection to database failed: " . $e->getMessage());
}

Have tried escaping everything with [] and specifying the database name before table name, but keep getting

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 '2017-08-11 (name, surname, email, 
phone, comment) VALUES ('Test', 'Test', 'Test@' at line 1
like image 686
NoSock Avatar asked Jul 26 '26 21:07

NoSock


2 Answers

INSERT INTO $date

It seems that there is a 2017-08-11 in $date var.

If you want to insert data into '2017-08-11' table, it should be escaped with ` symbol

try{
    $statement = $db->prepare("INSERT INTO `$date` (name, surname, email, phone, comment) VALUES (:name, :surname, :email, :phone, :comment)");
    $statement->bindParam(':name', $name);
    $statement->bindParam(':surname', $surname);
    $statement->bindParam(':email', $email);
    $statement->bindParam(':phone', $phone);
    $statement->bindParam(':comment', $comment);

    $statement->execute();
}
catch(PDOException $e){
    die("Connection to database failed: " . $e->getMessage());
}
like image 112
iXCray Avatar answered Jul 29 '26 12:07

iXCray


Assuming that 2017-08-11 is a table name, simply encase it in backticks.

    $statement = $db->prepare("INSERT INTO `$date` (name, surname, email, phone, comment) VALUES (:name, :surname, :email, :phone, :comment)");
like image 40
Altimus Prime Avatar answered Jul 29 '26 11:07

Altimus Prime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!