如何解决获取为 express js 勾选了复选框的项目的字段总和
我有一个食品清单,我希望能够通过勾选相应的复选框从列表中选择项目,然后计算其字段的总和,例如我有名为卡路里、碳水化合物、脂肪、蛋白质、盐、糖的字段,如果我在列表中选择两个项目并单击计算按钮,它将打印卡路里、碳水化合物、脂肪、蛋白质、盐、糖的总和两个项目。
<!doctype html>
<html>
<head>
<title>List foods page</title>
</head>
<body>
<h1> List foods page </h1>
<h3>display all foods stored in the database including name,typical values,unit of the typical value,calories,carbs,fat,protein,salt,and sugar of the food item here:</h3>
<ul>
<% availableFood.forEach(function(food_item){ %>
<form method="POST" action="/topic7/mid-term/calculate">
<p><input type="checkBox" name="checkBox" value=<%= food_item.name %>>
<input id="qty" type="text" name="qty" value="quantity"/>
<%= food_item.name %>,<%= food_item.typical_values %>,<%= food_item.unit_of_the_typical_value %>,<%= food_item.calories %>,<%= food_item.carbs %>,<%= food_item.fat %>,<%= food_item.protein %>,<%= food_item.salt %>,<%= food_item.sugar %></p>
</form>
<% }) %>
<form method="POST" action="/topic7/mid-term/calculate">
<input type="submit" value="Calculate sum" />
</form>
</ul>
</body>
</html>
app.post("/calculate",function (req,res) {
let sqlquery = "SELECT SUM(calories,sugar) FROM food_item WHERE name = ?";
let sum = [req.body.checkBox];
db.query(sqlquery,sum,(err,result) => {
if (err) {
return console.error(err.message);
}else{
res.send(" The nutritional information and calorie count of a recipe or a meal is: " + result);
}
});
});
解决方法
在 SQL 语句中使用集合而不是单个值,并与 IN
而不是 =
进行比较。
总和需要单独计算。用 AS
为它们命名,使结果更易于阅读。
let sqlquery = "SELECT SUM(calories) AS calories,SUM(carbs) AS carbs,SUM(fat) AS fat FROM food_item WHERE name IN (?)";
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。