php - How do I display a total from a menu form
问题描述
Im creating a food menu to practice php and sql databases. In my database I have food names and given prices for those foods.in my table I have a number input box that asks the users to enter a quantity for the amount of food they want. After the user clicks the submit button it will display the total amount, How do I do this.
This is my database info
CREATE TABLE product
(
productname
varchar(30) NOT NULL,
price
double NOT NULL,
)
INSERT INTO product
(productname
, price
) VALUES
('Pizza', 3.99),
('Fires', 1.99),
('water', 0.99),
('Cheese Balls', 2.99),
('Hot Dog', 2.99);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table,
tr,
th,
td {
border: solid 1px black;
}
</style>
</head>
<body>
<?php
echo '<form action="">';
echo"<h1>Food Menu</h1>";
$conn = mysqli_connect("localhost","root","","FoodMenu") or die("Missing Input. Go back and enter ID or Name");
$query = "select productname,price from product" ;
$r= mysqli_query($conn, $query);
echo"<p></p>";
echo"<table>";
echo"<tr><th>product</th><th>price</th><th>Quantity</th></tr>";
while($row = mysqli_fetch_assoc($r)){
printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>", $row["productname"],$row["price"], '<input type="number" id="quantity" name="quantity" value="0" min="0" max="5">');
}
echo"</table>";
echo '<p><input type="submit">';
echo '</form>';
?>
</body>
</html>
解决方案
您可以在 while 循环之前创建一个变量,并在 while 循环内对其应用增量,如下所示:
$total = 0.00;
while($row = mysqli_fetch_assoc($r)){
printf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>", $row["productname"],$row["price"], '<input type="number" id="quantity" name="quantity" value="0" min="0" max="5">');
$total += $row["price"];
}
//and then you can print the total price below the table or inside it like this:
print "<strong>Total: $total</strong>";
您还应该确保避免在代码中注入 mysql 。
推荐阅读
- javascript - 动态 Jquery 聚焦
- php - WooCommerce 股票的哪些挂钩已保存或更新
- c# - Azure Active Directory 与 WebForms 的集成在登录时获得无限循环
- bitbucket - 如何从选定的提交中引用 BitBucket 中的一行代码,但该行不是更改的一部分
- vb.net - VB.NET Selenium 如何获得跨度的特定值
- git - 删除 git repo 和跟踪文件
- python - 使用 QLineEdit.selectAll 后如何保持打字的能力?
- javascript - 为什么映射“parseInt”无点样式不能按预期工作?
- vba - MS Access 报告中的 Code128
- php - 无法使用 PHP 7.3 将 laravel 7 部署到 Google Cloud Platform