douzao9845 2013-03-25 12:12 采纳率: 0%
浏览 23
已采纳

从php中的输入字段向现有表添加列

I use pdo and mysql and I already know how to add a column to an existing table, but when I try it with value from an input field, the name of the variable $.... is being added as column.
The code I have to add the value from the input field as column, is as followed:

public function insertAlterTable($colName)
{
    $this->pdo = $this->connectMySql();
    $query = 'ALTER TABLE nbs_events ADD $colName CHAR(5) NULL DEFAULT "nee"';
    $stmt = $this->pdo->prepare($query);
    if(!$stmt->execute()){
        return false;
    }
    $this->pdo = null;
    return true;
}

This code is wrapped inside a try catch block.
And also inside a class.
At the frontpage I use this code like:

insertAlterTable($_POST['colname']);

How can I add the value from the input field colname as column to the existing table.
Please help.

I've updated the code as followed, so it works for me:

public function insertAlterTable($colName)
{ 
    $colName = mysql_real_escape_string($colName);
    $this->pdo = $this->connectMySql();
    $query = "ALTER TABLE nbs_events ADD $colName CHAR(5) NULL DEFAULT \"nee\"";
    $stmt = $this->pdo->prepare($query);
    if(!$stmt->execute()){
        return false;
    }
    $this->pdo = null;
    return true;
}
  • 写回答

1条回答 默认 最新

  • duanjianlu0506 2013-03-25 12:14
    关注

    In PHP, when using single quotes, variables are not expanded.

     $a = "hello";
     $b = "$a dude";               // $b is now "hello dude"
     $c = '$a dude';               // $c is now "$a dude"
    

    Use double quotes or string concatenation and you are fine:

     $query = "ALTER TABLE nbs_events ADD $colName CHAR(5) NULL DEFAULT \"nee\"";
    

    More in The Fine Manual: http://php.net/manual/en/language.types.string.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch