微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

获取为 express 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,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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?