怎么解决? ER_BAD_FIELD_ERROR:“字段列表”中的未知列“ undefined”

时间:2019-02-12 16:29:47

标签: mysql node.js express

我正在尝试使用expressjs将表单数据插入到nodejs中的MySQL数据库中

当我在命令提示符下运行代码时,它运行良好,但是当我按下“提交”按钮时,出现以下错误:

<i class="material-icons"> list </i>

我在MySQL命令行中创建了一个表

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password:'',
  database : 'test'
});

app.get("/", function(req, res){
        res.render("home");
});

//when I press submit button it should post the request and render a page to submit route with text "data saved!!" 

app.post("/submit", function(req, res){

  var q = "Insert into test (ID, name, crash1, crash2, crash3) VALUES (null, '" + req.body.ANR + "', " + req.body.crash1 + ", " + req.body.crash2 + ", " + req.body.crash3 +")";
  connection.query(q, function(err){
      if(err) throw err
      res.render("home", {message: 'data saved!!'});
  })
});

当我手动插入时它起作用了!

create table xyz(
    ID BIGINT AUTO_INCREMENT PRIMARY KEY NOT NULL, 
    name VARCHAR(100) NOT NULL, 
    crash1 BIGINT, 
    crash2 BIGINT, 
    crash3 BIGINT
);

我的错误看起来像这样 enter image description here

1 个答案:

答案 0 :(得分:0)

您要在代码中插入测试表:

var q = "Insert into test (ID, name, crash1, crash2, crash3) VALUES (null, '" + req.body.ANR + "', " + req.body.crash1 + ", " + req.body.crash2 + ", " + req.body.crash3 +")";

但是表名是xyz。您应该用xyz代替test,它应该可以工作。

并且不要在id中传递null,并且id不为null。

请将crash1,crash2,crash3转换为int值:

req.body.crash1 = parseInt(req.body.crash1);
req.body.crash2 = parseInt(req.body.crash2);
req.body.crash3 = parseInt(req.body.crash3);

应为:

var q = "Insert into xyz (name, crash1, crash2, crash3) VALUES ('" + req.body.ANR + "', " + req.body.crash1 + ", " + req.body.crash2 + ", " + req.body.crash3 +")";