2015-02-11 60 views
-3

我試圖將學生數據插入以父鍵作爲外鍵的表中。父數據在同一個JSON對象中發送,其中包含一個學生數組。我想選擇通過將父數據寫入數據庫發送的同一對象的父Id,然後選擇地址和名字與發送的相同的Id。另外如果你認爲我應該採取更有效的方式,歡迎。另外,我對節點以及HTTP服務器的工作原理也很陌生。 代碼獲取JSON對象如何在節點js的MySQL查詢中使用多個變量

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]); 
    } 
} 

任何幫助是巨大的。謝謝你的時間!

+0

我的意思是,如果該參數選項不工作,你總是可以回落到connection.escape(...) – 2015-02-11 19:12:45

回答

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]) 
} 
相關問題