douke9545 2014-02-18 14:29
浏览 50
已采纳

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

When I run this code:

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

I get the following error:

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

Note: $addUniverseColumn->execute(); is the line 63.

I have little to no idea as to what the problem is. I've searched for an answer to the problem but I can't find anything. Any help would be appreciated. :)

  • 写回答

1条回答 默认 最新

  • dousi2013 2014-02-18 14:36
    关注

    Placeholders can only work for VALUES, never field/table names. You cannot use a placeholder for the field name in an ALTER query. You'll have to use good old string interpolation for it:

    $db->prepare("ALTER TABLE spaceships ADD $name int");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型