向表中添加列会返回错误,指出SQL语法中的错误

时间:2014-02-18 14:29:03

标签: php mysql sql pdo

当我运行此代码时:

$addUniverseColumn = $db->prepare("ALTER TABLE spaceships ADD :universe int");
$addUniverseColumn->bindParam(":universe", $name);
$addUniverseColumn->execute();

我收到以下错误:

Fatal error: Uncaught exception 'PDOException' with message '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 ''asfa' int' at line 1' in D:\XAMPP\htdocs\php\locationconfig.php:63 Stack trace: #0 D:\XAMPP\htdocs\php\locationconfig.php(63): PDOStatement->execute() #1 {main} thrown in D:\XAMPP\htdocs\php\locationconfig.php on line 63

注意:$addUniverseColumn->execute();是第63行。

我几乎不知道问题是什么。我已经找到了问题的答案,但我找不到任何东西。任何帮助,将不胜感激。 :)

1 个答案:

答案 0 :(得分:1)

占位符只适用于VALUES,而不适用于字段/表名称。您不能在ALTER查询中使用占位符作为字段名称。你必须使用好的旧字符串插值:

$db->prepare("ALTER TABLE spaceships ADD $name int");