node.js - 获取勾选了 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, carbs, fat, protein, salt, 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 (?)";
推荐阅读
- tensorflow - 张量流乘以两层
- python - 如何使用 Boto Python 从 S3 获取最新文件的最后修改日期?
- jodatime - joda DateTimeFormat 本地时区格式问题
- java - 如何自动将所有 Lucene TermQuery 对象转换为 PrefixQuery?
- python - numpy argmin 向量化
- r - GGPlot2 - 绘制过零的弧 (geom_arc)
- r - 使用 readLines 和 R 中的 tm-package 清理 Web 文本
- c# - 带有前导零的 ID 号的 MaskedTextBox
- python - 如何将面板数据中的列中的值替换为 Python 中列表中的值?
- python - pyspark 加入更多条件