【问题标题】:How to save a Javascript variable into a Mysql database in expressjs如何在 expressjs 中将 Javascript 变量保存到 Mysql 数据库中
【发布时间】:2014-01-19 05:30:51
【问题描述】:

请我对 node js 和 expressjs 框架非常陌生。我正在开发一个 Web 应用程序,但我被卡住了。我已经设置了所有数据库要求并且一切正常,现在我想将一些数据保存到数据库中,并且我将数据存储在一个变量中,但不幸的是存储在变量(MyID)中的数据没有保存。这是我的代码

var=我的ID

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

    var postData = {
       // MyID: req.body.txtemplyeeID************Get employee ID as a foreign Key and Insert it,
        EmployeeID:req.body.txtemployeeID,
        FatherName:req.body.txtfathersName,
        MotherName:req.body.txtMothersName,
        NameOfSpouse:req.body.txtSpouseName,
        SpouseAddress:req.body.txtSpouseAddress,
        ParentsAddress:req.body.txtParentsAddress,
        EmployeeAddress:req.body.txtEmployeeAddress

    };
    connection.connect();
    connection.query('SELECT MyID from employees where EmployeeID='+"'"+ postData.EmployeeID +"'" +'', function(err, rows, fields) {

        if (err) throw err;

        for (var i in rows)
        {
            var results = rows[i];
            MyID=results.MyID;
            console.log(MyID);

        }

    })

        connection.query('INSERT INTO EmployeeContacts(MyID,FatherName,MotherName,NameOfSpouse,SpouseAddress,ParentsAddress,EmployeeAddress) VALUES ('+"'"+ MyID +"'"+','+"'"+ postData.FatherName +"'" +','+"'"+ postData.MotherName +"'" +','+"'"+ postData.NameOfSpouse +"'" +','+"'"+ postData.SpouseAddress +"'" +','+"'"+ postData.ParentsAddress +"'" +','+"'"+ postData.EmployeeAddress +"'" +');',
        function(err,results){
            if(err)console.log(err);
            else
            console.log("Success");
            connection.end() ;
            res.redirect("/addContact");

        });

});

}

【问题讨论】:

  • 你有一个 SQL 注入漏洞。
  • 您的第二个查询在第一个查询完成之前运行
  • 退后一步,确保您的数据库连接本身正常工作,然后再进行动态查询。然后记录来自您的连接的响应。是不是出错了?它说什么?
  • 我的数据库连接工作正常,当我用原始数据替换变量 MyID 时,例如:2 它会保存,但是当我将 2 存储在 MyID 中时它不会保存。我认为 SLaks 是对的,但我真的不知道如何解决这个问题。

标签: javascript node.js express


【解决方案1】:

既然你有一个格式正确的对象,你应该使用:

connection.query('INSERT INTO EmployeeContracts SET ?', postData, function(err, results) {
  if (err) {
    console.error(err);
  } else {
    res.redirect('/addContract');
});

这样更安全、更清洁。 另外,我认为您不必在处理完查询后显式结束连接。

为了避免在第一个查询结束之前执行第二个查询,只需将它们拆分为两个函数,并将 MyId 作为回调传递给您使用发布数据创建的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 2017-09-17
    • 2015-10-05
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 2018-03-14
    相关资源
    最近更新 更多