[英]Calculating total amount of row from database
I am trying to calculate the total amount of all the prices I get from my database but I can't figure it out.我正在尝试计算从数据库中获得的所有价格的总金额,但我无法弄清楚。 Its a bill from a restaurant.这是一家餐馆的账单。
$parameters = array(':tafelnummer'=>$tafelnummer);
$sth = $pdo->prepare("select * from bestellingen WHERE Tafelnummer = '$tafelnummer'");
$sth->execute();
while($row = $sth->fetch())
{
echo "<tr> ";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Soort'] . "</td>";
echo "<td> " . $row['Price'] . "</td>";
echo "</tr> ";
}
The price wil give a result for each dish which I need a total amount for每道菜的价格都会给出一个结果,我需要一个总金额
SELECT SUM(Price) AS Totalamount
FROM bestellingen
WHERE Tafelnummer = '$tafelnummer'
use this query than get the Totalamount.使用此查询而不是获取 Totalamount。
Rather than going back to the database, you can keep an accumulator and then add a TOTAL line to the bill.您可以保留一个累加器,然后在帐单中添加一个 TOTAL 行,而不是返回数据库。
Also I have attempted to fix your SQL Injection issue.我还尝试修复您的 SQL 注入问题。
$sth = $pdo->prepare("select * from bestellingen WHERE Tafelnummer = :tn");
$sth->execute([':tn' => $tafelnummer]);
$tot = 0;
while($row = $sth->fetch()) {
echo "<tr> ";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Soort'] . "</td>";
echo "<td> " . $row['Price'] . "</td>";
echo "</tr> ";
$tot += (float)$row['Price'];
}
echo "<tr> ";
echo "<td> </td><td>TOTAL</td><td>$tot</td>";
echo "</tr> ";
Just use a variable $total and add each price into it in the while loop.只需使用变量 $total 并在 while 循环中将每个价格添加到其中。
$total=0;
while($row = $sth->fetch())
{
$total+=(int)$row["Price"];
echo "<tr> ";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Soort'] . "</td>";
echo "<td> " . $row['Price'] . "</td>";
echo "</tr> ";
}
Make sure your Price value is always integer.确保您的价格值始终为 integer。 It is not necessary to typecast to (int).不必强制转换为 (int)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.