错误 1054 - 在 WHERE 中用作字段的变量被用作列
Error 1054 - Variable used as field in WHERE is taken as column
我正在尝试更新 mysql 数据库,但是当我执行查询时出现错误,其中 var id(在 WHERE 中使用)用作列名。
我读错了吗?我必须解决什么问题才能让它发挥作用?
Console Log
var message = '';
var id = req.session.user.id;
console.log(req.session.user.id);
var post = req.body;
var worker= post.worker;
var farmer= post.farmer;
var soldier= post.soldier;
var defender= post.defender;
var sql= "UPDATE stats SET worker = `"+worker+"`, farmer = `"+farmer+"`, soldier = `"+soldier+"`, defender = `"+defender+"` WHERE `stats`.`id` = `"+id+"` ";
db.query(sql, function(err, results){
if(results){
res.send('/home/dashboard.ejs')
};
if(err){console.log(err)};
});
}
导致错误的直接原因是您试图使用反引号而不是单引号来转义文字值。您看到的错误消息暗示了这一点。但是,与其仅仅用单引号替换那些反引号,不如使用准备好的语句:
var sql = "UPDATE stats SET worker = ?, farmer = ?, soldier = ?, defender = ? WHERE id = ?";
db.query(sql, [worker, farmer, soldier, defender, id], function(err, results) {
if (results) {
res.send('/home/dashboard.ejs')
}
if (err) {
console.log(err)
}
});
试试这个:
var sql= "UPDATE stats SET worker = '"+worker+"', farmer = '"+farmer+"', soldier = '"+soldier+"', defender = '"+defender+"' WHERE id = "+id+" ";
我从末尾的 id 列名称中删除了反引号(不必要的),并用单引号而不是反引号正确地将字符串括起来。也不需要 table 名称。
我正在尝试更新 mysql 数据库,但是当我执行查询时出现错误,其中 var id(在 WHERE 中使用)用作列名。 我读错了吗?我必须解决什么问题才能让它发挥作用?
Console Log
var message = '';
var id = req.session.user.id;
console.log(req.session.user.id);
var post = req.body;
var worker= post.worker;
var farmer= post.farmer;
var soldier= post.soldier;
var defender= post.defender;
var sql= "UPDATE stats SET worker = `"+worker+"`, farmer = `"+farmer+"`, soldier = `"+soldier+"`, defender = `"+defender+"` WHERE `stats`.`id` = `"+id+"` ";
db.query(sql, function(err, results){
if(results){
res.send('/home/dashboard.ejs')
};
if(err){console.log(err)};
});
}
导致错误的直接原因是您试图使用反引号而不是单引号来转义文字值。您看到的错误消息暗示了这一点。但是,与其仅仅用单引号替换那些反引号,不如使用准备好的语句:
var sql = "UPDATE stats SET worker = ?, farmer = ?, soldier = ?, defender = ? WHERE id = ?";
db.query(sql, [worker, farmer, soldier, defender, id], function(err, results) {
if (results) {
res.send('/home/dashboard.ejs')
}
if (err) {
console.log(err)
}
});
试试这个:
var sql= "UPDATE stats SET worker = '"+worker+"', farmer = '"+farmer+"', soldier = '"+soldier+"', defender = '"+defender+"' WHERE id = "+id+" ";
我从末尾的 id 列名称中删除了反引号(不必要的),并用单引号而不是反引号正确地将字符串括起来。也不需要 table 名称。