如何在节点js中的MySQL查询中使用多个变量

时间:2015-02-11 19:07:06

标签: javascript mysql json node.js server-side

我正在尝试将学生数据插入到父键作为外键的表中。父数据在同一个JSON对象中发送,其中包含一个学生数组。我想通过将父数据写入数据库来选择发送的同一对象的父ID,然后选择地址和名字与发送的地址相同的Id。如果你认为我应该以更有效的方式做到这一点,欢迎它。此外,我对节点以及http服务器的工作原理还很陌生。 获取JSON对象的代码

router.post('/scholarship', function(req, res) {            //post request to /members... use as model for /application, etc
console.log('post to api/scholarship');
console.log(req);          //req.body is the data you handle (save to mysql database)
res.send(req.body);
scholarReq = (req.body);});

写入数据库的代码

function insertIntoStudent(jsonpack){
var parentId;
parentId = connectToDatabase.query("SELECT memberId FROM Members WHERE address = ? AND firstName = ?", [jsonpack.user.address , jsonpack.user.firstName]);
for (var i = 0; i > jsonpack.user.students.length; i++){
    if (jsonpack.user.student[i].first != ""){
        connectToDatabase.query("INSERT INTO Students(firstName) VALUES (?)",[jsonpack.user.student[i].first]);
    }
    if (jsonpack.user.student[i].last != ""){
        connectToDatabase.query("INSERT INTO Students(lastName) VALUES (?)",[jsonpack.user.student[i].last]);
    }
    if (jsonpack.user.student[i].grade != ""){
        connectToDatabase.query("INSERT INTO Students(grade) VALUES (?)",[jsonpack.user.student[i].grade]);
    }
    if (jsonpack.user.student[i].unit != ""){
        connectToDatabase.query("INSERT INTO Students(unit) VALUES (?)",[jsonpack.user.student[i].unit]);
    }
}   

任何帮助都很棒。谢谢你的时间!

1 个答案:

答案 0 :(得分:0)

如果我正确理解你的问题你的意思是这样的话

for (var i = 0; i > jsonpack.user.students.length; i++){
    var user = jsonpack.user.student[i];
    connectToDatabase.query("INSERT INTO Students(firstName,lastname,grade,unit) VALUES (?,?,?,?),[user.first,user.last,user.grade,user.unit])
}