首页 > 解决方案 > 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>

标签: phpsql

解决方案


您可以在 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 。


推荐阅读