【问题标题】:PDO MySQL prepared INSERT syntax errorPDO MySQL 准备 INSERT 语法错误
【发布时间】:2018-01-14 03:22:30
【问题描述】:

看过很多类似的问题,但还是不知道发生了什么。

我正在使用 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

【问题讨论】:

  • 表名2017-08-11是无效的,如果你真的有一个以日期为名字的表(如果是这样我很好奇为什么)你需要用引号将它包裹起来
  • 谢谢!这只是一个简单的预订系统,每天有一张桌子。

标签: php mysql sql pdo syntax-error


【解决方案1】:

插入 $date

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

如果要将数据插入到'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());
}

【讨论】:

  • JimL 在 cmets 对我做了同样的事情
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    抱歉,您在使用 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());
    }
    

    【讨论】:

    猜你喜欢
    • 2016-01-12
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    相关资源
    最近更新 更多