简体   繁体   中英

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

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());
}

假设2017-08-11是表名,只需将其用反引号括起来即可。

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

sorry but you can't use special character when using the prepare statement, so what MySQL is actually seeing is INSERT INTO $date (name, surname, email, phone, comment) VALUES (:name, :surname, :email, :phone, :comment) which will trigger a syntax error.

here is a quick solution

 try{
$db->query("INSERT INTO $date (name, surname, email, phone, comment) VALUES ($name, $surname, $email, $phone, $comment)");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM