我收到了SyntaxError:该行的无效或意外的令牌:
var databaseQuery = "INSERT INTO userinfo
我想知道是否有人可以帮助我格式化我的代码,因为这是我第一次使用MYSQL和javascript所以我不确定为什么这不起作用或者我使用正确的格式因为我见过谷歌上的不同例子并不确定哪种写法是正确的。
app.post('/registration', urlencodedParser, function(req, res) {
console.log(req.body);
var databaseQuery = "INSERT INTO userinfo
(firstName,lastName,email,birthmonth,birthday,birthyear,university,country,state,zip,password)
VALUES ('"
+ req.body.firstName +"','"
+ req.body.lastName +"','"
+ req.body.email +"','"
+ req.body.birthmonth +"','"
+ req.body.birthday +"','"
+ req.body.birthyear +"','"
+ req.body.university +"','"
+ req.body.country +"','"
+ req.body.state +"','"
+ req.body.zip +"','"
+ req.body.password +"')";
connection.query(databaseQuery, function(err, result) {
if (err) {
throw err;
}else{
console.log(result.affectedRows + "records updated.");
}
}
res.render('registration', {qs: req.query});
});
答案 0 :(得分:1)
出现语法错误是因为您尝试在多行中编写一个语句并且不允许这样做。如果你想这样做,那么你需要使用后面的刻度(`)字符来代替外部的双引号。您还可以在字符串中使用$ {}分隔符来包含任何JavaScript代码/变量。
我认为你的connection.query()中还有另一个语法错误 - 你需要关闭")"关闭回调/匿名函数。
这个修改过的版本怎么样?
app.post('/registration', urlencodedParser, function(req, res) {
console.log(req.body);
var databaseQuery = `INSERT INTO userinfo
(firstName,lastName,email,birthmonth,birthday,birthyear,university,country,state,zip,password)
VALUES ('${req.body.firstName}',
'${req.body.lastName}',
'${req.body.email}',
'${req.body.birthmonth}',
'${req.body.birthday}',
'${req.body.birthyear}',
'${req.body.university}',
'${req.body.country}',
'${req.body.state}',
'${req.body.zip}',
'${req.body.password}')`;
connection.query(databaseQuery, function(err, result) {
if (err) {
throw err;
}else{
console.log(result.affectedRows + "records updated.");
}
});
res.render('registration', {qs: req.query});
});