douzao9845
2013-03-25 12:12
浏览 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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题