PDO MySQL编写了INSERT语法错误

时间:2017-08-06 20:39:22

标签: php mysql sql pdo syntax-error

已经看到了大量类似的问题,但仍然无法找出正在发生的事情。

我正在使用PHP的PDO来准备这样的声明:

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

尝试使用[]转义所有内容并在表名前指定数据库名称,但不断获取

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

3 个答案:

答案 0 :(得分:5)

  

INSERT INTO $ date

似乎有一个2017-08-11 in $ date var。

如果您想将数据插入' 2017-08-11'表,它应该用`符号

进行转义
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());
}

答案 1 :(得分:2)

假设2017-08-11是一个表名,只需将其包含在反引号中。

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

答案 2 :(得分:-1)

抱歉,但是在使用prepare语句时你不能使用特殊字符,所以MySQL实际看到的是INSERT INTO $date (name, surname, email, phone, comment) VALUES (:name, :surname, :email, :phone, :comment)会触发语法错误。

这是一个快速解决方案

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